本文主要是介绍获取spring容器中管理的bean的方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
方式一:实现ServletContextListener
定义BeanContants,该类定义一个static变量,保存ApplicationContext的对象
public class BeanConstants {public static ApplicationContext context;}
在项目启动时,配置listener,将获取web工程当前的上下文信息(ApplicationContext)赋值为上面定义的变量。
public class StartupListener implements ServletContextListener {@Overridepublic void contextDestroyed(ServletContextEvent event) {// TODO Auto-generated method stub}@Overridepublic 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
这篇关于获取spring容器中管理的bean的方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!