十七、如何取得Spring管理的bean (请用第3种方法)
1、servlet方式加载时,
【web.xml】
spring容器放在ServletContext中的key是org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC
注意后面的springMVC,是你的servlet-name配置的值,注意适时修改。
Java代码
- ServletContext sc=略
- WebApplicationContext attr = (WebApplicationContext)sc.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC");
2、listener方式加载时:
【web.xml】
【jsp/servlet】可以这样取得
Java代码
- ServletContext context = getServletContext();
- WebApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(context);
3、通用的方法来了,神器啊,前的 1、2两种方法并不通用,可以抛弃了。
在配置文件中加入:
Java代码