Search code examples
jakarta-eenullpointerexceptioncdiinject

Java EE 6 Producer Not Working


I am using JBoss As 7 and Java EE 6. I have an empty beans.xml

I have a logger Producer like this..

@Singleton
@Startup
public class LoggerProducer {

     private static Logger logger = Logger.getLogger(LoggerProducer.class.getName());

    @Produces
    public Logger produceLogger(final InjectionPoint injectionPoint) {  
        final String injectingClass = injectionPoint.getMember().getDeclaringClass().getName();
        return Logger.getLogger(injectingClass);  
    }  

}

In my class i Inject as follows...

@Inject
Logger logger;

I import java util logger in each case

import java.util.logging.Logger;

Everything deploys correctly however the Injection of the logger is failing and I get a runtime NullPointer if i try to use the injected logger


Solution

  • Thanks to all for replies.

    I have beans.xml in the right place (WEB-INF). It is packaged as a .war.

    The issue was my own coding fault in the class(bean) i was injecting the logger into. I had mistakenly used a constructor to initialise the class which thus tried to use the logger before CDI had a chance to inject it

    The fix was to replace the constructor with a @PostConstruct method and all worked well.

    @MyAnnotation
    @Singleton
    public class MtHammer implements Hammer {
    
        .....
    
        @Inject
        Logger logger2;
    
    
        @PostConstruct
        private void startup() {
    
            initialise();
    
        }
    
         private void initialise() {
                logger.info("logger...Initialising ...");
          ....
            }