我有一个数据对象(只有吸气剂\设定部),其需要知道的弹簧简档,即Java Spring - 如何将@Value注入数据对象?
@Value("${spring.profiles.active}")
private String profile;
我添加了一个逻辑到它的一个“集”的方法,它检查轮廓,即
public void setItem(Item msg) {
if (environmentProperties.isDevMode()) {
this.msg= msg;
}
}
,因为这个类是经常元帅\ unmarhsalled外部,因此,当然没有被填充@Value - 正弦我没有使用弹簧自动装配创建类的实例...我试图定义的类作为组件,并自动装载到包含配置文件@Value的外部类 - 但它不起作用 我使用spring 3.2 - 没有XML定义。
有什么建议吗?
b.t.w. 数据对象经常包装在一个异常类中 - 所以当它创建时,配置文件也应该被数据对象知道...
谢谢!
编辑:
- 使用了ApplicationContextAware不工作 - 我得到空的 'setApplicationContext' 方法不会被调用。
- 也试图直接获取上下文不起作用 - 使用时取代null: 'ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();'
FIXED: 我终于找到了一个例子如何staticly从外部类访问上下文:
@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')? – Daniel