spring-从普通java类取得注入spring Ioc容器的对象的方案

java

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");  

以上是 spring-从普通java类取得注入spring Ioc容器的对象的方案 的全部内容, 来源链接: utcz.com/z/393247.html

回到顶部