项目打包成功,但是放入tomcat运行失败,原因有可能是Filter过滤器注入bean实例时注入失败为null

原因:

在Spring的自动注入中普通的POJO类都可以使用@Autowired进行自动注入,但是除了两类:Filter和Servlet无法使用自动注入属性。(因为这两个归tomcat容器管理)可以用init(集承自HttpServlet后重写init方法)方法中实例化对象。

注意:使用Tomcat war运行才会报这个错,SpringBoot jar运行不影响哦

其实Spring中,web应用启动的顺序是:listener->filter->servlet,先初始化listener,然后再来就filter的初始化,再接着才到我们的dispathServlet的初始化,因此,当我们需要在filter里注入一个注解的bean时,就会注入失败,因为filter初始化时,注解的bean还没初始化,没法注入。

private SLoyApiMessageMapper sLoyApiMessageMapper;

方法1:

 @Override
public void init(FilterConfig arg0) throws ServletException {

        ServletContext sc = arg0.getServletContext();
        XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);

        if(cxt != null && cxt.getBean("SLoyApiMessageMapper") != null && sLoyApiMessageMapper == null){
            sLoyApiMessageMapper = (SLoyApiMessageMapper) cxt.getBean("SLoyApiMessageMapper");
    }
        LOGGER.debug("decode过滤器init");
	}

方法2:

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("SLoyApiMessageMapper") != null && 
         sLoyApiMessageMapper== null)
            sLoyApiMessageMapper= (SLoyApiMessageMapper) cxt.getBean("SLoyApiMessageMapper");
        
}


参考文章:如何在java Filter中注入Service

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值