十七、如何取得Spring管理的bean (请用第3种方法)

1、servlet方式加载时,
【web.xml】

十七、如何取得Spring管理的bean (请用第3种方法)

 spring容器放在ServletContext中的key是org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC
注意后面的springMVC,是你的servlet-name配置的值,注意适时修改。

Java代码 

  1. ServletContext sc=略  
  2. WebApplicationContext attr = (WebApplicationContext)sc.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC");  

 

2、listener方式加载时:
【web.xml】

十七、如何取得Spring管理的bean (请用第3种方法)

【jsp/servlet】可以这样取得

Java代码 

  1. ServletContext context = getServletContext();  
  2. WebApplicationContext applicationContext  = WebApplicationContextUtils .getWebApplicationContext(context);   

 

3、通用的方法来了,神器啊,前的  1、2两种方法并不通用,可以抛弃了。
在配置文件中加入:

十七、如何取得Spring管理的bean (请用第3种方法)

Java代码

十七、如何取得Spring管理的bean (请用第3种方法)

十七、如何取得Spring管理的bean (请用第3种方法)