简体   繁体   中英

Spring Boot - add external property files

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.

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.

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

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.

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;

    }
}

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 { ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM