NullPointerException 在 @Produces 方法中获取 bean 类名

ps0*_*604 2 java logback slf4j java-ee-8 jakarta-ee

我将此类LoggerProducer注入到@Statelessbean 中以生成日志条目,如此处所述

问题是,当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
    }   

}
Run Code Online (Sandbox Code Playgroud)

注入记录器的bean:

import org.slf4j.Logger;

@Stateless
@LocalBean
@Named
public class CustomerBean  {

    @Inject
    private Logger logger;

    ......
      logger.info("some message");
Run Code Online (Sandbox Code Playgroud)

Car*_*Way 5

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

@Produces 
Logger createLogger(InjectionPoint injectionPoint) { 
    return LoggerFactory.getLogger( injectionPoint.getMember().getDeclaringClass().getName() );
}
Run Code Online (Sandbox Code Playgroud)