Spring Boot - add external property files

早过忘川 提交于 2019-12-24 11:36:39

问题


I have simple MVC application in SpringBoot, created using java-config (I don't have web.xml).
That application have DB connection based on JPA. Until now, all was great, but now I must move db.properties from inside of WAR to location specified by OS variable ("CONFIG_LOCATION").

In spring doc is written about that not too much. There is only say that it is posible, but how I should set that in my Spring application?
I suppose that should be done before initializer.

Then I see only two options:
- SpringApplication - there is somewhere a place where I should insert files location from OS variable but I can't find it,
- some annotation, that will understond OS variable, and add files from it to spring context before EntityManager will be created.

I'm open to suggestion how should I do that.


回答1:


As mentioned in another answer @PropertySource annotation is the way to go (I'll add some details). In Java 8 you can apply it several times to your configuration class, and the order matters! For example you can make this configuration:

@SpringBootApplication
@PropertySource("classpath:/db.properties")
@PropertySource(ignoreResourceNotFound = true, value = "file:${MY_APP_HOME}/db.properties")
@PropertySource(ignoreResourceNotFound = true, value = "file:${user.home}/.myapp/db.properties")
@ComponentScan("com.myorg")
public class Application {
     // ....
}

Here I assume that you should have MY_APP_HOME environment variable, and also you might want to place some settings in user home. But both configs are optional because of ignoreResourceNotFound set to true.

Also note on the order. You may have some reasonable settings for development environment in src/main/resources/db.properties. And put specific settings in host OS where your production service runs.

Look at the Resolving ${...} placeholders within @PropertySource resource locations section in javadoc for details.




回答2:


If you are using the config parameters of spring-boot, it is just to specify the config location on execute jar or war, with parameter --spring.config.location.

Example:

$ java -jar myproject.jar --spring.config.location=/opt/webapps/db.properties




回答3:


If you just want Spring to reference an external properties file under your project root.
Here is a simpler solution:

@Configuration
@PropertySource("file:${user.dir}/your_external_file.properties")
public class TestConfig {
  @Autowired
  Environment env;
}

You can change the ${user.dir} to ${user.home} if necessary.




回答4:


Ok, I found a way.

I created class what return PropertySourcesPlaceholderConfigurer.
In that PSPC i get OS variable, and scan all files in that location.
After scan I was add all files with properties extension to PSCS as locations.
Method is @Bean, and class is @Configuration. After that all works fine :)

imports...

@Configuration
public class AppServiceLoader {
    @Bean(name = "propLoader")
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();

        String mainConfigPath = StringUtils.isNotEmpty(System.getenv("CONFIG_LOCATION"))
                ? System.getenv("CONFIG_LOCATION") : System.getProperties().getProperty("CONFIG_LOCATION");

        File configFolder = new File(mainConfigPath);

        if(configFolder.isDirectory()) {
            FilenameFilter ff = new FilenameFilter() {

                @Override
                public boolean accept(File file, String string) {
                    return string.endsWith(".properties");
                }
            };
            File[] listFiles = configFolder.listFiles(ff);
            Resource[] resources = new Resource[listFiles.length];
            for (int i = 0; i < listFiles.length; i++) {
                if(listFiles[i].isFile()) {
                    resources[i] = new FileSystemResource(listFiles[i]);
                }
            }
            pspc.setLocations(resources);
        }

        pspc.setIgnoreUnresolvablePlaceholders(true);
        return pspc;

    }
}



回答5:


You can also use the annotation @PropertySource. It's more clear and clean than the code solution.

See: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html

For instance:

@Configuration @PropertySource("classpath:/com/myco/app.properties") public class AppConfig { ...



来源:https://stackoverflow.com/questions/29013760/spring-boot-add-external-property-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!