1.启动服务时通过spring容器的监听器(继承ContextLoaderListener 监听器的方法)
public class ListenerSpringContext extends ContextLoaderListener { private final Logger log = LoggerFactory.getLogger(ListenerSpringContext.class); public void contextInitialized(ServletContextEvent event) { log.info("init ListenerSpringContext..."); super.contextInitialized(event); ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); //自己手动保留一个spring注入的容器 UtilsSpringContext.setApplicationContext(applicationContext); } }
2.实现appctionContextaware的方法
package com.ceopen.eoss.spring; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext context) throws BeansException { SpringUtil.applicationContext = context; } public static Object getBean(String name){ return applicationContext.getBean(name); } }
将SpringUtil注入spring配置文件
<bean id="spring" class="com.ceopen.eoss.spring.SpringUtil" />
获取
ICBMission icbMission = (ICBMission)SpringUtil.getBean("ICBMission");
时间: 2024-10-05 07:24:16