简体   繁体   中英

How to configure Spring to load application.properties from outside of jar?

I'd like to have a directory structure as so:

/Directory
    - Application.jar
    - application.properties

So that I can change properties without having to repackage and redeploy (and instead just restarting the jar). How can I accomplish this with spring annotations or configuration classes?

I'm not asking about making external resources available with my web application, I'm also looking to change the location from where spring loads the application.properties file.

You're mentioning jar, so you're using Spring Boot?

If so, external application.properties in the same directory (structure just like you described) will override application.properties packaged inside the jar file.

Then, if you have something like key=value in your application.properties, you can inject it in your code with @Value("${key}") String key .

Try it, it will just work :)

You may want to explore PropertyPlaceholderExplorer class in Spring. This class provides the facility to access the properties file external to your jar/war bundle. There is a short nice tutorial on this as well here .

If you start using Spring Boot (at some stage you for sure will). you get powerful configuration externalization features .

With Spring Boot your applications.properties are automatically loaded into Spring Boot context and you can use ${...} placeholders.

You can use even more modern feature @ConfigurationProperties to map you configuration to POJO. This POJO can even be validated by Java EE validation annotations (eg @NotNull)

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