在任何地方调用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,