starcraftOnCrack
starcraftOnCrack

Reputation: 79

spring boot adding another properties file to the environment

I was wondering if it was possible to add another properties file to the environment path besides just the application.properties file. If so how do you specify the new path? So you can access the properties using the Autowired Environment variable. Currently in my java project the default properties file application.properties have the path /soctrav/src.main.resources/application.properties

Upvotes: 6

Views: 7459

Answers (3)

Philemon Hilscher
Philemon Hilscher

Reputation: 189

I've found a solution that makes the properties available in the spring environment as well as providing support for using them in @Value("${my.custom.prop}")

@Bean
protected PropertySourcesPlaceholderConfigurer createPropertyConfigurer(ConfigurableEnvironment environment)
        throws IOException {
    PropertySourcesPlaceholderConfigurer result = new PropertySourcesPlaceholderConfigurer();

    FileUrlResource resource = new FileUrlResource(Paths.get("custom-props.properties").toString());
    result.setLocation(resource);
    try (InputStream is = resource.getInputStream()) {
        Properties properties = new Properties();
        properties.load(is);
        environment.getPropertySources().addFirst(new PropertiesPropertySource("customProperties", properties));
    }
    return result;
}

This is very useful when you are not in a spring boot autoconfigured environment but have access to basic spring features.

Upvotes: 0

jayb0b
jayb0b

Reputation: 179

If you want to do it without command line parameters, this will do the trick.

@SpringBootApplication
@PropertySources({
        @PropertySource("classpath:application.properties"),
        @PropertySource("classpath:anotherbunchof.properties")
})
public class YourApplication{

}

Upvotes: 8

luboskrnac
luboskrnac

Reputation: 24591

You can specify additional property files with command line parameters:

java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

Take a look at Application properties file Spring Boot doc chapter.

Upvotes: 3

Related Questions