我将这个LoggerProducer类注入到@Stateless bean中,以生成日志条目,如here所述。

问题是,当调用CustomerBean时(甚至不调用logger.info),@Produces方法(检索bean类名)将失败,并显示NullPointerException。此代码有什么问题?

@Named
@Singleton
public class LoggerProducer {

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

}


注入记录器的bean:

import org.slf4j.Logger;

@Stateless
@LocalBean
@Named
public class CustomerBean  {

    @Inject
    private Logger logger;

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

最佳答案

假设injectionPoint不为null(在生产者方法中),则可以尝试以下操作:

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

10-08 19:46