【问题标题】:How to access Spring managed properties from bean's methods?如何从 bean 的方法访问 Spring 托管属性?
【发布时间】:2011-03-04 18:23:53
【问题描述】:

我在 .properties 文件中有属性列表。 现在我正在使用PropertyPlaceholderConfigurer 管理这些属性文件。

我想从其中一种方法中访问属性值。 谁能建议如何实现这一目标?

例子

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

现在我已经通过指定 connection.properties 配置了 `PropertyPlaceholderConfigurer bean

我有一种方法可以根据部署模式读取 url 所以基于部署模式,我想使用属性文件更改 url。

如果这是正确的方法,请告诉我。

如果您有任何建议,请给予。

【问题讨论】:

    标签: java spring


    【解决方案1】:

    PropertyPlaceholderConfigurerdoes not expose 的属性。但是,您可以使用例如轻松地重新读取属性文件。 PropertiesLoadUtils

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

    【讨论】:

      【解决方案2】:

      也许您正在寻找类似@Value 注释的东西?

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

      【讨论】:

        【解决方案3】:

        不清楚您在寻找什么,但我有一个实用程序,它可以根据运行环境(开发、产品)加载属性

        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();
            }
        

        那么你需要将bean定义为

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

        您需要在机器上定义一个环境条目,键为“ENV_NAME”

        例如:ENV_NAME=prod

        windows 环境变量和 .profile 中的 unix 条目。

        您需要按照以下方式维护每个环境的属性 prod-jms.properties uat-jms.properties

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-09-03
          • 2012-05-22
          • 2014-12-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-30
          相关资源
          最近更新 更多