如何解决使用 xml 配置为 Servlet 过滤器注入空 bean
我为 spring 安全创建了 JWT 过滤器。 当应用程序运行时,过滤器被执行,应该被注入的字段为空(SessionDao 和 TokenService) 对于那些类(SessionDao 和 TokenService),我添加了注释,它们运行良好,也添加到 spring-config.xml Beans
<bean id="sessionDao" class="com.dao.impl.SessionDaoImpl" scope="prototype"/>
<bean id="tokenService" class="com.service.impl.TokenServiceImpl" scope="prototype"/>
也在尝试@Autowired
其他过滤器效果很好(CorsFilter(没有注入的字段))
下面的 JwtFilter 类
@Component
@NoArgsConstructor(force = true)
@AllArgsConstructor
public class JwtFilter extends GenericFilterBean {
private static final String AUTHORIZATION_HEADER = "Authorization";
private final SessionDao sessionDao;
private final TokenService tokenService;
private final Logger log = new LoggerUtil().getLogger();
@Override
public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain
filterChain) throws IOException,servletexception {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String token = request.getHeader(AUTHORIZATION_HEADER);
try {
Authentication authentication = tokenService.getAuthentication(token);
if (authentication != null) {
AuthorizedUser authorizedUser = (AuthorizedUser) authentication.getPrincipal();
SessionEntity session = sessionDao.getByJwtId(authorizedUser.getJwtId());
if (!session.isDeleted()) {
session.setLastActivityTime(new Timestamp(System.currentTimeMillis()));
sessionDao.save(session);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
} catch (Exception ignored) {
}
filterChain.doFilter(request,response);
}
}
由 web.xml 启用 .... 科尔斯 rsoft.component.SimpleCORSFilter
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>JwtFilter</filter-name>
<filter-class>com.component.JwtFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>JwtFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
如果我在 JwtFilter @NoArgsConstructor (force = true) 或类中的默认构造函数中删除,则会出现编译错误,因为 JwtFilter 类的默认构造函数将保留在 web.xml 中 在那一行
<filter-class>com.component.JwtFilter</filter-class>
提前致谢!
解决方法
问题是context还没有bean,如果使用xml配置,要么手动编写bean创建,要么使用注解
public void init(FilterConfig cfg) {
ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(cfg.getServletContext());
this.bean = ctx.getBean(YourBeanType.class);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。