在servelt中取得spring注入对象的方法
方法1:
1、先在web.xml中定义加载applicationContext.xml的listener2、在servlet中可用此取得User对象
WebApplicationContext ctx=WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
User user = (User)ctx.getBean( "user ");
String userName = user.getUserName();
方法二:
1.在web.xml中自定义一个listener
<!-- listener初始化spring注入 -->
<listener>
<listener-class>cn.com.cardinfo.report.tools.listener.ContextListener</listener-class>
</listener>
2.自定义listener的写法
package cn.com.cardinfo.report.tools.listener;
import javax.servlet.*;
import cn.com.cardinfo.report.tools.main.MainCase;
import java.util.*;
public class ContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
MainCase.init(); //初始化加载spring的方法
}
public void contextDestroyed(ServletContextEvent event) {
}
}
3.自定义init方法 这是一个取巧的方法,在web.xml中自定义一个listener并在监听容器启动的时候加载init方法
init是一个在类中指定ApplicationContext.xml中profile获得context的方法
这样,做完之后,就会在容器加载的时候,就获取到context(这个方法之只用于 因为某种原因,spring不能自定注入的特殊案例)
private static ApplicationContext context;
public static ReportDataBean process(String path) throws Exception {
// 获得导入导出控制类
Controller controller = context.getBean(Controller.class);
// 处理路径为服务器上的upload文件夹
ReportDataBean bean = controller.process(path);
return bean;
}
public static void init() {
if (context == null) {
System.setProperty("spring.profiles.active", "production");
context = new ClassPathXmlApplicationContext(
"classpath:applicationContext.xml");
}
}