代码之家  ›  专栏  ›  技术社区  ›  ps0604

在@products方法中获取bean类名的nullpointerException

  •  1
  • ps0604  · 技术社区  · 6 年前

    我有这个 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");
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Carlitos Way    6 年前

    假设 injectionPoint 不为空(在Producer方法中),可以尝试以下操作:

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