开发者

Load Spring bean

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

I've a appContext file having lots of beans. When loading it using the following code, it loads all beans again.

BeanFactory factory = ne开发者_运维知识库w ClassPathXmlApplicationContext("appContext.xml");


What 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 like this;

SpringApplicationContext.getBean("myBean");


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

I would recommend you to split you spring configuration in several distinct files. In that case you'll be able to load only that group of beans which is required for your task.

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

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


You can use ApplicationContextAware interface. example

When you get instance of this bean, you can load whatever bean you want.


One method is to migrate to using springs abstraction of quartz. That way, your quartz "jobs" are spring beans from the start.

Read more here.


This may help in order to avoid having to recreate a spring context.

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

For example, if you use the MethodInvokingJobDetailFactoryBean, then you could create a bean that executes 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜