需求:在一个类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");