【发布时间】:2016-03-28 06:43:20
【问题描述】:
我有一个需要了解 Spring 配置文件的数据对象(仅带有 getters\setter),即
@Value("${spring.profiles.active}")
private String profile;
我在其中一个“设置”方法中添加了一个逻辑来检查配置文件,即
public void setItem(Item msg) {
if (environmentProperties.isDevMode()) {
this.msg= msg;
}
}
因为这个类经常在外部编组\unmarhsalled,所以,当然@Value 没有被填充 - 因为我没有使用spring Autowire来创建类实例......我尝试将类定义为组件,并自动连接到保存配置文件 @Value 的外部类 - 但它不起作用 我使用 spring 3.2 - 没有 XML 定义。
有什么建议吗?
顺便说一句。 数据对象通常包装在异常类中 - 所以当它创建时,数据对象也应该知道配置文件......
谢谢!
已编辑:
- 使用 ApplicationContextAware 不起作用 - 我得到 null 'setApplicationContext' 方法从未被调用。
- 尝试直接获取上下文也不起作用 - 使用以下命令时获取 null: 'ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();'
固定: 我最终找到了一个如何从外部类静态访问上下文的示例:
@Configuration
public class ApplicationContextContainer implements ApplicationContextAware {
private static ApplicationContext CONTEXT;
/**
* This method is called from within the ApplicationContext once it is
* done starting up, it will stick a reference to itself into this bean.
*
* @param context a reference to the ApplicationContext.
*/
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
CONTEXT = context;
}
/**
* This is about the same as context.getBean("beanName"), except it has its
* own static handle to the Spring context, so calling this method statically
* will give access to the beans by name in the Spring application context.
* As in the context.getBean("beanName") call, the caller must cast to the
* appropriate target class. If the bean does not exist, then a Runtime error
* will be thrown.
*
* @param beanName the name of the bean to get.
* @return an Object reference to the named bean.
*/
public static Object getBean(String beanName) {
return CONTEXT.getBean(beanName);
}
【问题讨论】:
-
你试过@DependsOn('yourPropertiesBeanName')吗?