Java 使用<;上下文:属性占位符>;工厂法
我已经编写了一个工厂bean,它根据特定于应用程序的属性文件中配置的属性创建缓存管理器 其概念是可以选择多个实现,每个实现使用其他配置属性 例如:Java 使用<;上下文:属性占位符>;工厂法,java,spring,properties,Java,Spring,Properties,我已经编写了一个工厂bean,它根据特定于应用程序的属性文件中配置的属性创建缓存管理器 其概念是可以选择多个实现,每个实现使用其他配置属性 例如: noop缓存,不带参数 带有#max对象的ehcache 配置了多个IP和端口的memcache 我认为最好不要在application context.xml中指定所有缓存应用程序特定的参数,而是从现有的属性源中读取它们 我尝试使用环境软件接口访问环境。但是使用配置的属性文件似乎不包含在属性资源中 例如:属性 cache.implementat
- noop缓存,不带参数
- 带有#max对象的ehcache
- 配置了多个IP和端口的memcache
application context.xml
中指定所有缓存应用程序特定的参数,而是从现有的属性源中读取它们
我尝试使用环境软件
接口访问环境
。但是使用
配置的属性文件似乎不包含在属性资源中
例如:属性
cache.implementation=memcached
cache.memcached.servers=server1:11211,server2:11211
application-context.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;
}
}
公共类CacheManagerFactory实现FactoryBean,环境感知{
私人环境保护署;
@凌驾
public CacheManager getObject()引发异常{
字符串impl=env.getRequiredProperty(“cache.implementation”);//此操作失败
//基于impl执行一些操作,这需要更多属性。
}
@凌驾
公共环境(环境环境){
this.env=env;
}
@凌驾
公共类getObjectType(){
返回CacheManager.class;
}
@凌驾
公共布尔isSingleton(){
返回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>
其中,your.properties包含以下内容:
cities = my test string
property1.email = answer@stackvoerflow.com
我认为你没有抓住我问题的重点。我希望能够在“我的工厂”方法中访问由
定义的属性。@HafkensitE您是否有理由不能使用第二种方法我的postedIt可能是因为每个缓存实现都有很多配置参数。我希望能够对相同的编译类使用不同的配置。如果我理解正确,我必须在我的应用程序中指定所有参数/属性Contexti我真的不理解您的问题,多个属性和属性文件相对简单。谢谢您回答的“代码中”部分。这正是我想要的-如何从spring junit集成测试中以编程方式引用属性。您使用的是哪个版本的spring?我认为他们在3.1版中对此进行了改进
cities = my test string
property1.email = answer@stackvoerflow.com