【企业应用--spring】在任何地方调用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" class="context.ApplicationContextProvider"></bean>

 

 4、此时就可以在任意地方调用spring中配置的bean.调用方法如下:

 

ApplicationContext ctx = AppContext.getApplicationContext();   
//honey 为配置到spring中的bean的id
Honeypotbean honey = (HoneyPotBean) ctx.getBean("honey");  
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值