读书人

在任何地方调用spring配备的bean

发布时间: 2012-08-30 09:55:54 作者: rapoo

在任何地方调用spring配置的bean

需求:在一个类A里调用spring配置的bean,但类A没有配置到sping中。

?

解决方法:

1、创建“ApplicationContextProvider”类,代码如下:

?

package context;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;/** This class provides an application-wide access to the   * Spring ApplicationContext! The ApplicationContext is   * injected in a static method of the class "AppContext".   * Use AppContext.getApplicationContext() to get access   * to all Spring Beans.   */public class ApplicationContextProvider implements ApplicationContextAware {public void setApplicationContext(ApplicationContext ctx) throws BeansException {AppContext.setApplicationContext(ctx);}}

?

?2、创建“AppContext”类,代码如下:

?

import org.springframework.context.ApplicationContext;/** This class provides application-wide access to the Spring ApplicationContext.  * The ApplicationContext is injected by the class "ApplicationContextProvider".   * */public class AppContext {private static ApplicationContext ctx;/** Injected from the class "ApplicationContextProvider" which is automatically  *  loaded during Spring-Initialization.      */public static void setApplicationContext(ApplicationContext applicationContext) {ctx = applicationContext;}/** Get access to the Spring ApplicationContext from everywhere in your Application.       *  @return      **/public static ApplicationContext getApplicationContext() {return ctx;}} // .EOF  

?

?3、修改applicationContext.xml,增加如下配置

?

<bean id="contextApplicationContextProvider" name="code">ApplicationContext ctx = AppContext.getApplicationContext();   //honey 为配置到spring中的bean的idHoneypotbean honey = (HoneyPotBean) ctx.getBean("honey");  
?

?

1 楼 wellbbs 2011-04-17 现在是可以取到了,我写的这个单例里可以使用spring里注册的bean,
但是这个单例在jsp页面使用时候报
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
错误 2 楼 wellbbs 2011-04-17 后来改了只能调用
@Transactional
里的方法就没有问题了

读书人网 >软件架构设计

热点推荐