2

我有这个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
    }   

}

注入记录器的bean:

import org.slf4j.Logger;

@Stateless
@LocalBean
@Named
public class CustomerBean  {

    @Inject
    private Logger logger;

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

1 回答 1

5

假设它injectionPoint不为空(在你的生产者方法中),你可以试试这个:

@Produces 
Logger createLogger(InjectionPoint injectionPoint) { 
    return LoggerFactory.getLogger( injectionPoint.getMember().getDeclaringClass().getName() );
}
于 2019-01-20T11:08:23.217 回答