Spring and @Autowired on a DelegatingFilterProxy

后端 未结 2 445
你的背包
你的背包 2021-01-04 12:46

I\'m trying to inject a spring bean into a filter, but can\'t make it work.

The bean injected is always \"null\". I succeed autowiring this same bean in Controllers

2条回答
  •  -上瘾入骨i
    2021-01-04 12:57

    Try to explicitly define the name for your CheckSession bean and see if that helps... Like this:

    @Component("CheckSession")
    public class CheckSession extends OncePerRequestFilter implements Filter {
        @Autowired private Usuario usuario;
    
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                HttpServletResponse response, FilterChain chain)
                throws ServletException, IOException {
    
            //  always null
            System.out.println("autowired " + usuario);
            chain.doFilter(request,  response);
        }
    }
    

    The key part is this: @Component("CheckSession")

    And to make things prettier and easier to deal with down the road, I would camelCase the name and rename it to "checkSession" everywhere (de-capitalize first letter).

提交回复
热议问题