NullPointerException getting bean class name in @Produces method

333 views Asked by At

I have this LoggerProducer class that's injected in a @Stateless bean to generate log entries as explained here.

Problem is that when CustomerBean is invoked (without even calling logger.info), the @Produces method (that retrieves the bean class name) fails with NullPointerException. What is wrong with this code?

@Named
@Singleton
public class LoggerProducer {

    @Produces
    public Logger produceLogger(InjectionPoint injectionPoint) {
        return LoggerFactory.getLogger(
                   injectionPoint.getBean().getBeanClass()); // <- error here
    }   

}

The bean that injects the logger:

import org.slf4j.Logger;

@Stateless
@LocalBean
@Named
public class CustomerBean  {

    @Inject
    private Logger logger;

    ......
      logger.info("some message");
1

There are 1 answers

0
Carlitos Way On BEST ANSWER

Assuming that injectionPoint is not null (in your producer method), you can try this:

@Produces 
Logger createLogger(InjectionPoint injectionPoint) { 
    return LoggerFactory.getLogger( injectionPoint.getMember().getDeclaringClass().getName() );
}