我有一個bean可以掃描註解了特定註解的類(特定於域的一個)。我想確保所有用@MyDomainAnnotation
註釋的bean在掃描bean註釋爲@MyDomainAnnotation
的bean之前被初始化並實例化。Spring IoC容器 - 定義對使用特定註釋進行註釋的類的依賴性?
有沒有一種方法來定義這種依賴關係,因爲這是框架的一部分,因此新類可能會「插入」。基本上我不會事先知道班級的名字。
我有一個bean可以掃描註解了特定註解的類(特定於域的一個)。我想確保所有用@MyDomainAnnotation
註釋的bean在掃描bean註釋爲@MyDomainAnnotation
的bean之前被初始化並實例化。Spring IoC容器 - 定義對使用特定註釋進行註釋的類的依賴性?
有沒有一種方法來定義這種依賴關係,因爲這是框架的一部分,因此新類可能會「插入」。基本上我不會事先知道班級的名字。
在您的掃描bean上執行ApplicationListener<ContextRefreshedEvent>
。
public class MyScanningBean implements ApplicationListener<ContextRefreshedEvent> {
private boolean scanned = false;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
/* Published when the ApplicationContext is initialized or refreshed,
* for example, using the refresh() method on the
* ConfigurableApplicationContext interface. "Initialized" here means
* that all beans are loaded, post-processor beans are detected and
* activated, singletons are pre-instantiated, and the
* ApplicationContext object is ready for use. */
if (!scanned) {
// scan for beans
scanned = true;
}
}
}
雖然我選擇了實現ApplicationListener作爲@Tichodroma建議我還發現了另一種解決方案,它有時可能是你想要什麼,如果你需要一些更細粒度的控制豆類的秩序初始化。因此,執行SmartLifecycle可以提供相位值,這些值將確定bean實例化的順序(按升序排列)(即具有最小相位值的bean將首先被初始化)。
但無論如何,我認爲上述答案在我的情況下更優雅和乾淨。
考慮到'ContextRefreshedEvent'可以被觸發多次。 – Bart
感謝您的提示。我已經添加了一張支票。 – 2013-07-29 13:26:33