开发者

How to access Spring managed properties from bean's methods?

开发者 https://www.devze.com 2023-02-15 01:25 出处:网络
I have list of properties mantianed in .properties file. Now I am managing those property file wiht PropertyPlaceholderConfigurer.

I have list of properties mantianed in .properties file. Now I am managing those property file wiht PropertyPlaceholderConfigurer.

I want to access property value from one of the method. Can anyone please suggest how to achieve that?

example

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

Now I have configured `PropertyPlaceholderConfigurer bean by specifing connection.properties

I have one method which reads url based on mode of deplo开发者_运维问答yment so base on mode of deployment I want to change url using property file.

Please let me know if this is right approach.

If you have any suggestion please give.


The PropertyPlaceholderConfigurer does not expose its properties . You could however easily read in the properties file anew using e.g. PropertiesLoadUtils:

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


Maybe you're looking for something like the @Value annotation?

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


Not clear what you are looking for, but I have utility where it loads properties based on environment its running 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 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 a environment entry on machine with key as "ENV_NAME"

Ex: ENV_NAME=prod

In case of windows environment variable and in case of unix entry in .profile.

You need to maintain properties for each environment in following fashion prod-jms.properties uat-jms.properties

0

精彩评论

暂无评论...
验证码 换一张
取 消