NullPointerException 在@Produces 方法中获取 bean class 名称

NullPointerException getting bean class name in @Produces method

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

问题是当调用 CustomerBean 时(甚至没有调用 logger.info),@Produces 方法(检索 bean class 名称)失败并显示 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 不为空(在你的生产者方法中),你可以试试这个:

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