Spring boot 2.2 打成 war 包 过滤器或者拦截器 注入失败

2020-07-10 09:26:21 +08:00
 qw564518158
第一次发帖,好像不能上图,就尴尬了。
因为 jar 包的顺序和 war 的加载顺序不同。

Filter 里面注入失败。

解决方法在 init 初始化这里对 Service 进行手动注入

public class RESTApiAuthenticationFilter implements Filter {

protected Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ApiUserService apiUserService;
@Autowired
private SignaConfig signaConfig;

@Override
public void init(FilterConfig filterConfig) {
logger.info("RESTApiAuthentication filter has been launched!");
//手动注入
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext());
signaConfig = factory.getBean(SignaConfig.class);
apiUserService = factory.getBean(ApiUserService.class);
}

@Override
public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse,
FilterChain chain) throws IOException, ServletException {
}

@Override
public void destroy() {
// TODO Auto-generated method stub

}
}

在 Filter 初始化的时候手动注入即可。
这个问题已经馋了我三天三夜了
2230 次点击
所在节点    程序员
14 条回复
mosliu
2020-07-10 09:31:35 +08:00
用 @Order(1000 ) 自己定义注入顺序应该就可以了吧
hfc
2020-07-10 10:19:01 +08:00
注入失败有异常抛出嘛?有个 DependsOn 的注解,不知道有没有用。
xuanbg
2020-07-10 10:28:13 +08:00
可以曲线救国,在另一个 Abc 类里面注入,这个类写个 @Component 就会被扫到自动实例化。然后在 Filter 里面用 ApplicationContextHolder.getContext().getBean(Abc.class)获取 Abc 的实例。
codingbody
2020-07-10 12:02:37 +08:00
不懂就问,为啥不用 jar 而是用 war ?
hantsy
2020-07-10 13:32:48 +08:00
看不出来你的 Filter 是哪里注册的。WebXML ?

Servlet 中的 Servlet,Filter 等在 Spring Boot 中可以直接声明为 Component/Bean,Spring Boot 会帮你的注册。
qw564518158
2020-07-10 14:18:00 +08:00
@mosliu 还有这等操作?下次试试看
WhenAtRains
2020-07-10 14:37:20 +08:00
应该是自动注入 @Autowired 的事情
WhenAtRains
2020-07-10 14:41:18 +08:00
我记得这个错是要看 localhost_accessxxxx 的日志才能在网上找到答案。看 catalina 日志看不出来
ala2008
2020-07-10 15:00:50 +08:00
是的,上下文不一样
hantsy
2020-07-10 18:00:10 +08:00
另外,可能 Instanise 顺序的问题,在加载 Filter 的时候,依赖可以没有实例。
用 @Autowired 加上 @Lazy 。最新的 Spring 2.2 可以开启全局 Lazy Loading,提高启动速度。
wucao219101
2020-07-10 18:27:34 +08:00
@codingbody 可能是为了用 jsp
qw564518158
2020-07-15 16:30:48 +08:00
@hfc 没异常,但是显示 null,空指针异常
@codingbody 因为另外一些项目都是 SSM,现在分裂出了一个新的服务,才搞成微服务,为了方便运维管理吧
qw564518158
2020-07-15 16:32:45 +08:00
@hantsy
@Lazy
@Autowired
private SignaConfig signaConfig;
测试了一下还是不行
hantsy
2020-07-15 16:35:53 +08:00
@wucao219101 jsp 太恐怖了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/688757

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX