【发布时间】:2012-09-28 17:05:35
【问题描述】:
我编写了一个工厂 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;
}
}
【问题讨论】:
-
您使用的是哪个版本的 Spring?我认为他们在 3.1 版中改进了这一点blog.springsource.com/2011/02/15/…
标签: java spring properties