仅启动applicationcontext中所有bean的子集

时间:2011-04-27 10:34:52

标签: java spring

我们有一个设置,其中ApplicationContext定义了很多bean,但根据情况,只需要启动这些bean的子集(并且通过启动我的意思是Lifecycle回调和start()方法)。 p>

基本上,我想要做的是在单个bean上调用“start”,并使该bean的所有依赖项在常规bean启动顺序中启动,但没有别的。

这样的东西有没有现成的代码?如果没有,那么实现这个的好方法是什么?

3 个答案:

答案 0 :(得分:2)

我通常将bean配置拆分为单独的文件,然后只导入包含必要bean的文件。如果可以避免循环依赖,则可以将文件相互导入。例如,您可以像这样定义一个service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <description>Service and lower layer beans.</description>

    <context:component-scan base-package="com.gamma.purple"
        use-default-filters="false">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Service" />
    </context:component-scan>

    <import resource="dao.xml" />

</beans>

由于dao.xml应该没有依赖于service.xml,如果你只想要dao bean,你可以只导入该文件,而不会加载服务bean。

答案 1 :(得分:2)

您还可以在bean上设置延迟初始化,以便在必要时加载它们。来自http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/beans.html#beans-factory-lazy-init的bean节点示例:

<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>

答案 2 :(得分:0)

您可以将bean的子集分离到单独的xml文件中,并使用它来创建新的spring应用程序上下文。这个新上下文可以引用在应用程序启动期间初始化的主应用程序上下文(以及它们中定义的bean)。

ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{...}, parentContext);
// once you have finished using it, close the context
ctx.close();