asp做网站的步骤,广告设计专业烧钱吗,新闻头条最新消息摘抄,做网站分什么软件From: https://www.cnblogs.com/EasonJim/p/7666009.html
在Spring的自动注入中普通的POJO类都可以使用Autowired进行自动注入#xff0c;但是除了两类#xff1a;Filter和Servlet无法使用自动注入属性。#xff08;因为这两个归Web容器管理#xff09;可以用init#xf…From: https://www.cnblogs.com/EasonJim/p/7666009.html
在Spring的自动注入中普通的POJO类都可以使用Autowired进行自动注入但是除了两类Filter和Servlet无法使用自动注入属性。因为这两个归Web容器管理可以用init集承自HttpServlet后重写init方法方法中实例化对象。
解决方法
其中涉及到五种Spring实例化容器对象
方法一这种方式不符合Web工程不要使用在初始化时保存ApplicationContext对象
ApplicationContext ac new FileSystemXmlApplicationContext(applicationContext.xml);
ac.getBean(beanId);
说明这种方式适用于采用Spring框架的独立应用程序需要程序通过配置文件手工初始化Spring的情况。
方法二这种方式最简单通过Spring提供的工具类获取ApplicationContext对象 import org.springframework.web.context.support.WebApplicationContextUtils;ApplicationContext ac1 WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean(beanId);
ac2.getBean(beanId); 说明这种方式适合于采用Spring框架的B/S系统通过ServletContext对象获取ApplicationContext对象然后在通过它获取需要的类实例。上面两个工具方式的区别是前者在获取失败时抛出异常后者返回null。
实例 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req (HttpServletRequest)request;HttpServletResponse resp (HttpServletResponse)response;ServletContext sc req.getSession().getServletContext();XmlWebApplicationContext cxt (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);if(cxt ! null cxt.getBean(usersService) ! null usersService null)usersService (UsersService) cxt.getBean(usersService);Users users this.usersService.queryByOpenid(openid); public class WeiXinFilter implements Filter{private UsersService usersService;public void init(FilterConfig fConfig) throws ServletException {ServletContext sc fConfig.getServletContext(); XmlWebApplicationContext cxt (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);if(cxt ! null cxt.getBean(usersService) ! null usersService null)usersService (UsersService) cxt.getBean(usersService); } 注意如果在Spring Boot项目上XmlWebApplicationContext可以不用要直接使用WebApplicationContext替代。
方法三继承自抽象类ApplicationObjectSupport
说明抽象类ApplicationObjectSupport提供getApplicationContext()方法可以方便的获取到ApplicationContext。
Spring初始化时会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext对象注入。
方法四继承自抽象类WebApplicationObjectSupport
说明类似上面方法调用getWebApplicationContext()获取WebApplicationContext
方法五实现接口ApplicationContextAware
说明实现该接口的setApplicationContext(ApplicationContext context)方法并保存ApplicationContext 对象。Spring初始化时会通过该方法将ApplicationContext对象注入。 参考
http://blog.csdn.net/angel708884645/article/details/51148865
http://www.cnblogs.com/digdeep/p/4770004.html
如有问题请联系我easonjim#163.com或者下方发表评论。