我有一個數據對象(只有吸氣劑\設定部),其需要知道的彈簧簡檔,即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