我编写了一个工厂 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/