Returning null in Bean annotated method

236 Views Asked by At

I have a web filter that I only want to execute when debug level is enabled. I was trying to implement a dummy filter to return to conform to Null Object pattern but I was getting many errors and lost hours. The solution below seems to work seamlessly but I wonder what happens if @Bean method returns null? Is this safe?

   @Bean
    WebFilter payloadFilter() {
        if(log.isDebugEnabled()) {
            return new PayloadFilter();
        }else{
            return null;
        }
    }
1

There are 1 best solutions below

0
On

Of course, returning null is not a good idea, you should avoid it. I don't know how logging in your application is controlled, but if you setup logging level via application.yml, I would do something like this:

@Bean
@ConditionalOnProperty(prefix = "logging.level", name = "com.example.config", havingValue = "DEBUG")
public WebFilter payloadFilter() {
    return new PayloadFilter();
}