java - 使用 <context :property-placeholder> in a factory method 定义的属性

标签 java spring properties

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

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

例如:

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

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

我的尝试是使用 EnvironementAware访问 Environement 的界面.但似乎使用 <context:property-placeholder> 配置的属性文件不包含在 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;
    }

}

最佳答案

在这样的配置文件中:

 <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

关于java - 使用 <context :property-placeholder> in a factory method 定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12781868/

相关文章:

java - 整数输入中的下划线导致java出错

java - 合并排序中合并的测试用例

java - Ant-task 不适用于 java 9

java - Gradle无法在Java项目中复制PNG文件

java - 有哪些使用 Spring 和 Hibernate 的优秀示例应用程序?

java - 异步 API 性能更差

java - Spring AOP - 带有注释的每个方法的切入点

java - 实例化 Java 对象

c# - 使用另一个接口(interface)属性的 IList 实现接口(interface)的类...如何?

python - 可以使用字符串来引用对象属性吗?