Spring在Java Filter注入Bean为Null的问题解决
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,或者下方發表評論。<==
總結
以上是生活随笔為你收集整理的Spring在Java Filter注入Bean为Null的问题解决的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: fgui的ui管理框架_FGUI,UGU
- 下一篇: std::string删除首字符