Download Spring bean

Is there any way in Spring to load a bean in particular.

I have an appContext file with lots of beans. When loaded with the following code, it loads all the beans again.

BeanFactory factory = new ClassPathXmlApplicationContext("appContext.xml"); 
+4
source share
5 answers

How about using ApplicationContextAware ?

Bean mapping

<bean id="springApplicationContext" class="SpringApplicationContext"/>

Java implementation

 public class SpringApplicationContext implements ApplicationContextAware { private static ApplicationContext CONTEXT; public void setApplicationContext(ApplicationContext ctx) throws BeansException { CONTEXT = ctx; } public static Object getBean(String name) { return CONTEXT.getBean(name); } } 

Then use it as follows:

SpringApplicationContext.getBean("myBean");

+4
source

By default, spring creates instances of all singleton -scoped beans at startup.

I would recommend you split the spring configuration into several different files. In this case, you can only download the beans group that is required for your task.

Another way is to declare your beans with the default-lazy-init attribute:

 <beans default-lazy-init="true"> <!-- no beans will be pre-instantiated... --> </beans> 
+2
source

You can use the ApplicationContextAware interface. example

When you get an instance of this bean, you can load any bean.

0
source

One way is to use abstraction of quartz springs. So your quartz "quests" are spring beans from the start.

More details here .

0
source

This can help to avoid re-creating the spring context.

If you use Spring to configure the quartz job , you can reference spring beans directly from your work.

For example, if you use MethodInvokingJobDetailFactoryBean , then you can create a bean that runs the code, which in turn calls your DAO.

 <bean id="exampleBusinessObject" class="my.pkg.BusinessObject"> <property name="dao" ref="myDao" /> </bean> <bean id="exampleJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="exampleBusinessObject"/> <property name="targetMethod" value="doIt"/> </bean> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="exampleJob" /> <!-- run every 30 min --> <property name="cronExpression" value="0 0/30 * * * ?" /> </bean> 
0
source

All Articles