0

I use spring to inject DemoService has always been null, there is no problem with the filter inject of servlet, in the class of extends TurboFilter, how can I get the DemoService object?

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

I have tried the answer to this connection and did not solve the problem of inject.

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;
    }
}
取一个好的名字
  • 1,677
  • 14
  • 16

3 Answers3

0

Problem: Logback starts up before the Spring context. Therefore you need to lazy initialize the Filter with the to be injected bean. Apart from that the Filter will not be called as a Spring bean, but as a Turbofilter, that does not know any injections and so on.

What you could try is define that Filter as a Spring bean in your context, that contains the DemoService. Inject the bean via a Setter for the service, but declare the field static, so you are able to access it from the logging context.

Now during the execution you need to check if the static field is already initialized, if so you can use it without a problem.

markusw
  • 1,975
  • 16
  • 28
0

You are not trying the answer you are quoting, because your extended filter "ErrorLogTurboFilter" does not have a "@Named("errorLogTurboFilter")" which is the standard annotation to make your filter a spring bean.

see : What is javax.inject.Named annotation supposed to be used for?

Tristan
  • 8,733
  • 7
  • 48
  • 96
  • I have already tried, the package is import org.mapstruct.Named, I don't know if this package is correct.Service can be started, but the inject is null – 取一个好的名字 Dec 05 '18 at 09:31
  • Nope, like you can see in my "see :" the package is not correct ;) You can just use "@Component" btw, @Named is just a "standard" jdk non-spring alternative. – Tristan Dec 05 '18 at 09:39
  • If this answered your question, you should mark it as "validated". – Tristan Dec 05 '18 at 21:06
0

@markusw According to your prompt, this is my solution,and thank you.

@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;
}

}

取一个好的名字
  • 1,677
  • 14
  • 16