【问题标题】:Using properties defined by <context:property-placeholder> in a factory method在工厂方法中使用 <context:property-placeholder> 定义的属性
【发布时间】:2012-09-28 17:05:35
【问题描述】:

我编写了一个工厂 bean,它根据应用程序特定属性文件中配置的属性创建缓存管理器。

这个概念是可以选择多个实现,每个实现都使用其他配置属性。

例如:

  • noop 缓存,无参数,
  • 带有#max 个对象的ehcache
  • 配置了多个 ips 和端口的 memcache。

我认为最好不要在application-context.xml 中指定所有缓存应用程序特定的参数,而是从现有的属性源中读取它们。

我的尝试是使用EnvironementAware 接口来访问Environement。但是使用&lt;context:property-placeholder&gt;配置的属性文件似乎没有包含在PropertiesSources中。

example.properties

cache.implementation=memcached
cache.memcached.servers=server1:11211,server2:11211

应用程序上下文.xml

<context:property-placeholder location="example.properties"/>
<bean id="cacheManager" class="com.example.CacheManagerFactory"/>

在 CacheManagerFactory.java 中

public class CacheManagerFactory implements FactoryBean<CacheManager>, EnvironmentAware {

    private Environement env;

    @Override
    public CacheManager getObject() throws Exception {
        String impl = env.getRequiredProperty("cache.implementation"); // this fails
    //Do something based on impl, which requires more properties.
    }

    @Override
    public void setEnvironment(Environment env) {
        this.env = env;
    }

    @Override
    public Class<?> getObjectType() {
        return CacheManager.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

}

【问题讨论】:

标签: java spring properties


【解决方案1】:

在这样的配置文件中:

 <context:property-placeholder location="classpath:your.properties" ignore-unresolvable="true"/>
  ...
 <property name="email" value="${property1.email}"/>
 <!-- or -->
 <property name="email">
   <value>${property1.email}</value>
 </property>

或在代码中:

@Value("${cities}")
private String cities;

your.properties 包含此内容的位置:

cities = my test string 
property1.email = answer@stackvoerflow.com

【讨论】:

  • 我不认为你明白我的问题的重点。我希望能够在我的工厂方法中访问由&lt;context:property-placeholder&gt; 定义的属性。
  • @HafkensitE 有没有理由你不能使用我发布的第二种方法
  • 可能每个缓存实现我都有很多配置参数。而且我希望能够对相同的编译类使用不同的配置。如果我理解正确,我将不得不在我的应用程序上下文中指定所有参数/属性
  • 我不太明白你的问题,多属性和属性文件比较简单。
  • 感谢您回答的“代码中”部分。这正是我一直在寻找的 - 如何在 spring junit 集成测试中以编程方式引用属性。
猜你喜欢
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多