0

我用spring注入DemoService一直为null,servlet的filter注入没有问题,在extends TurboFilter的类中,如何获取DemoService对象?

https://stackoverflow.com/questions/30662641/inject-spring-bean-into-custom-logback-filter

我已经尝试了这个连接的答案,并没有解决注入的问题。

public class ErrorLogTurboFilter extends TurboFilter {

    @Autowired
    private DemoService demoService;


    @Override
    public FilterReply decide(Marker marker, Logger logger, Level level, String s, Object[] objects, Throwable throwable) {

        // todo
         return FilterReply.NEUTRAL;
    }
}
4

3 回答 3

0

问题:Logback 在 Spring 上下文之前启动。因此,您需要使用要注入的 bean 延迟初始化过滤器。除此之外,Filter 不会被称为 Spring bean,而是称为 Turbofilter,它不知道任何注入等。

您可以尝试在您的上下文中将 Filter 定义为 Spring bean,其中包含DemoService. 通过服务的 Setter 注入 bean,但声明字段static,因此您可以从日志记录上下文中访问它。

现在在执行过程中,您需要检查静态字段是否已经初始化,如果是,您可以毫无问题地使用它。

于 2018-12-05T09:13:17.687 回答
0

您没有尝试引用的答案,因为您的扩展过滤器“ErrorLogTurboFilter”没有“@Named("errorLogTurboFilter")”,这是使您的过滤器成为 spring bean 的标准注释。

请参阅:javax.inject.Named 注释应该用于什么?

于 2018-12-05T09:26:28.677 回答
0

@markusw 根据您的提示,这是我的解决方案,谢谢。

@Configuration
public class WebConfig {

    @Bean
    public DemoService demoService() {
        return new DemoService();
    }
}
public class ErrorLogTurboFilter extends TurboFilter {


    private ApplicationContext ctx = new AnnotationConfigApplicationContext(WebConfig.class);
    private DemoService demoService = ctx.getBean(DemoService.class);


@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String s, Object[] objects, Throwable throwable) {

    // todo
     return FilterReply.NEUTRAL;
}

}

于 2018-12-06T03:29:26.440 回答