Spring:如何确保bean注册到容器的顺序?

时间:2016-03-28 03:31:41

标签: spring

我有一组服务类,它们分布在我的应用程序中的不同maven模块中。

public class ServiceA implements IsService
{
   public void startA()
   {
       ....
   }
}

public class ServiceB implements IsService
{
   public void startB()
   {
       ....
   }
}

创建配置类以仅检测和注册实现IsService接口的类。

@Configuration
@ComponentScan(basePackages = {"com.subex.roc"} , 
              useDefaultFilters = false , 
              includeFilters = {@Filter(type = FilterType.ASSIGNABLE_TYPE,value = IsService.class)})
public class ServiceRegisterConfig 
{
}

获取已注册的类并以多态方式调用start()。

  public void initServerServices()
    {
        AnnotationConfigApplicationContext context = new  AnnotationConfigApplicationContext();
        context.register(ServiceRegisterConfig.class);
        context.refresh();

        for (String beanDfn : context.getBeanDefinitionNames()) 
        {
          if (context.getBean(beanDfn) instanceof IsService) {
          IsService service = (IsService) context.getBean(beanDfn);
          service.start();
        }
     } 
    }

但是我想确保首先调用ServiceA的start(),然后ServiceB作为ServiceB依赖于ServiceA的初始化。容器可以以某种方式确保这一点吗?

尝试取决于。但是,在classpath.DependsOn遇到它们的顺序中调用的服务的start()不被尊重。

2 个答案:

答案 0 :(得分:0)

使用depends-on属性,但如果遇到麻烦,您可以随时入侵后处理器工厂......

public class PreInitializer implements BeanFactoryPostProcessor, PriorityOrdered {  
 @Override  
 public int getOrder() {  
  return Ordered.HIGHEST_PRECEDENCE;  
 }  
 @Override  
 public void postProcessBeanFactory(  
   ConfigurableListableBeanFactory beanFactory) throws BeansException {  
  /* put initialization code here */  
 }  
}  

答案 1 :(得分:0)

BeanFactoryPostProcessor可用于设置依赖项

public class DependencyConfigurer implements BeanFactoryPostProcessor, PriorityOrdered {

    @Override  
 public int getOrder() {  
  return Ordered.HIGHEST_PRECEDENCE;  
 } 

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

            BeanDefinition bd = beanFactory.getBeanDefinition("serviceB");
            bd.setDependsOn("serviceA");


    }



}

您也可以使用DependsOn注释

@Bean(name="ServiceA") 
   public class ServiceA implements IsService
    {
       public void startA()
       {
           ....
       }
    }

@Bean(name="ServiceB")
@DependsOn("ServiceA")
public class ServiceB implements IsService
{
   public void startB()
   {
       ....
   }
}

最后可以使用XML配置

<bean class="com.foo.ServiceA" name="serviceA"/>

<bean class="com.foo.ServiceB" depends-on="serviceA"/>