How to access Spring managed properties from bean methods?

I have a list of properties saved in a .properties file. Now I manage this wiht PropertyPlaceholderConfigurer property file.

I want to access the value of a property from one of the methods. Can anyone suggest how to do this?

Example

 connection.properties dev.url = "http://localhost:8080/" uat.url = "http://xyz.com" 

Now I have configured the `PropertyPlaceholderConfigurer bean by specifying connection.properties

I have one method that reads the url based on the deployment method so the base mode in deployment mode I want to change the url using the properties file.

Please let me know if this is the right approach.

If you have any suggestions, please let me know.

+4
source share
3 answers

PropertyPlaceholderConfigurer does not provide its properties. However, you can easily read the properties file again using, for example, PropertiesLoadUtils :

 PropertiesLoaderUtils.loadProperties( new ClassPathResource("/connection.properties")); 
+3
source

Maybe you are looking for something like @Value annotations?

 private @Value("#{connection.dev.url}") String myURL; 
+2
source

It's not clear what you're looking for, but I have a utility where it loads properties based on the environment it works on (dev, prod)

 public class EnvironmentalPlaceHolderConfigurer extends PropertyPlaceholderConfigurer implements InitializingBean { private Resource overrideLocation; public void setOverrideLocation(Resource overrideLocation) { this.overrideLocation = overrideLocation; } if(overrideLocation != null){ if( overrideLocation.exists()) super.setLocation(overrideLocation); else{ logger.warn("Unbale to find "+overrideLocation.getFilename() +" using default"); } }else{ logger.warn("Override location not set, using default settings"); } } @Override public void afterPropertiesSet() throws Exception { setProperLocation(); } 

Then you need to define a bean as

 <bean class="com.commons.config.EnvironmentalPlaceHolderConfigurer"> <property name="overrideLocation" value="classpath:/jms/${ENV_NAME}-jms.properties" /> <property name="location" value="classpath:/jms/jms.properties" /> </bean> 

You need to define the environment record on the machine with the key as "ENV_NAME"

Example: ENV_NAME = prod

In the case of a Windows environment variable and in the case of writing unix to .profile.

You need to maintain properties for each environment as follows prod-jms.properties uat-jms.properties

0
source

Source: https://habr.com/ru/post/1342334/


All Articles