我有一个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