方式一:实现ServletContextListener
定义BeanContants,该类定义一个static变量,保存ApplicationContext的对象
public class BeanConstants {
public static ApplicationContext context;
}
在项目启动时,配置listener,将获取web工程当前的上下文信息(ApplicationContext)赋值为上面定义的变量。
public class StartupListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
ApplicationContext applicationContext=WebApplicationContextUtils.getRequiredWebApplicationContext(context);
BeanConstants.context=applicationContext;
}
}
在web.xml中配置这个listener。
在需要获取某个bean时,比如我们在spring的配置文件中,
<bean id="userManager" class="com.*.*.UserManager"> </bean>
代码中通过BeanContants.getBean(“userManager”)获取这个bean
方式二:实现ApplicationContextAware
如果某个Bean实现了ApplicationContextAware接口,Spring容器会在创建该Bean之后,
自动调用该Bean的setApplicationContextAware()方法。
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext ctx;
@Override
public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException {
ctx = applicationContext;
}
/**
* @param beanName bean的名字
* @return 返回一个bean对象
*/
public static Object getBean( String beanName ) {
return ctx.getBean( beanName );
}
}
配置
<bean id="SpringApplicationContext" class="com.ningpai.common.util.ApplicationContextHelper">
</bean>
可以通过ApplicationContextHelper.getBean(“userManager”)方式获取spring容器中的bean