代码之家  ›  专栏  ›  技术社区  ›  DeepNightTwo

如何控制Springbean创建的顺序?

  •  2
  • DeepNightTwo  · 技术社区  · 10 年前

    我正在使用一些第三部分的罐子,这些罐子部分迁移到了春天。痛点是有很多初始化模块没有迁移到spring。在创建大量bean之前,需要首先执行初始化模块。

    我也阅读 Spring 3 bean instantiation sequence ,这里的问题是,第三部分库使用@Component创建bean(这取决于没有迁移到spring的初始化模块,wired right…?)。

    现在我可以编写一个spring bean来包装所有的初始化模块。并在需要它的bean之前创建bean。

    那么,有没有一种方法可以指定bean创建序列来首先创建初始化bean?

    我还检查了一些文档,springbean创建是在单线程中进行的,所以这可以工作。

    2 回复  |  直到 9 年前
        1
  •  1
  •   Sanj    10 年前

    您可以使用BeanPostProcessor并添加初始化模块作为依赖项

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
    
    <bean class="com.foo.CustomBeanPostProcessor" depends-on="com.foo.InitModuleBean"/>
    <bean class="com.foo.BarBean" />
    <bean id="com.foo.InitModuleBean" class="com.foo.InitModuleBean" />
    </beans>
    
        2
  •  0
  •   achabahe    10 年前

    您将初始化为xmlConfig文件中第一个Bean的wraperBean放入,然后spring将通过初始化该Wraper来处理初始化。另一个解决方案是添加 depends-on 属性添加到依赖于该包装器的所有bean,并在属性中指定该包装器bean的id 取决于 这样地

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="modules" class="com.mycompany.ModulesWrapper" />
    <bean class="com.foo.ClientBean" depends-on="modules" />
    </beans>