Spring IoC容器-定义对用特定注释注释的类的依赖关系



我有一个bean,它扫描用特定注释(特定于域的注释)注释的类。我想确保所有用@MyDomainAnnotation注释的bean都在扫描用@MyDomainAnnotation注释的bean之前初始化和实例化。

有没有一种方法可以定义这样的依赖关系,因为这是框架的一部分,因此可能会"插入"新的类。基本上,我事先不知道班级的名字。

在扫描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;
    }
  }
}

请参阅http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#context-功能事件

尽管我选择了按照@Tichodroma的建议实现ApplicationListener,但我也找到了另一种解决方案,如果您需要对bean的初始化顺序进行更细粒度的控制,有时可能就是您想要的。因此,在实现SmartLifecycle时,您可以提供阶段值,这些值将确定实例化bean的顺序(按升序)(即,具有最小阶段值的bean将首先初始化)。

但无论如何,我认为以上答案对我来说更优雅、更干净。

最新更新