Reputation: 4168
We have a setup where an ApplicationContext has a lot of beans defined, but depending on circumstances, only a subset of these beans need to be started (and by started I mean the Lifecycle callbacks and start() method).
Basically, what I'd like to do is to call "start" on a single bean, and have all the dependencies of that bean started in the regular bean startup order, but nothing else.
Is there any existing code for something like this? If not, what would be a good way to implement this?
Upvotes: 1
Views: 437
Reputation: 21000
You could separate out the subset of beans into a separate xml file and use it to create a new spring application context. This new context can refer to the main application context (and the beans defined within them) which is initialized during application startup.
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{...}, parentContext);
// once you have finished using it, close the context
ctx.close();
Upvotes: 0
Reputation: 4951
You can also set lazy initialization on beans, such that they're loaded when necessary. An example of a bean node from http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/beans.html#beans-factory-lazy-init:
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
Upvotes: 2
Reputation: 32407
I usually split the bean configuration into separate files and just import the file that contains the necessary beans. If you can avoid circular dependencies, you can import the files into each other. For example, you could have a service.xml defined like this
<?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>
Since dao.xml
should have no dependencies on service.xml, if you only wanted the dao beans, you could just import that file, and no service beans would be loaded.
Upvotes: 2