@Resource annotated member not injected - bad code or bug?
        Posted  
        
            by Brabster
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Brabster
        
        
        
        Published on 2010-04-30T16:11:10Z
        Indexed on 
            2010/04/30
            16:27 UTC
        
        
        Read the original article
        Hit count: 294
        
I am using an @Resource annotation in a class instantiated in a ServletContextListener's contextInitialized(...) method, but the member is always null. Here's my sample code.
Listener:
public void contextInitialized(ServletContextEvent sce) {
  System.err.println("In contextInitialised");
  new ResourceListenerTargetTest().executeMe(); 
}
ResourceListenerTargetTest:
@Resource(name="MyJDBCResource")
private DataSource source;
public void executeMe() {
  /*try {
    InitialContext ictx = new InitialContext();
    source = (DataSource)ictx.lookup("java:comp/env/MyJDBCResource");
  } catch (NamingException e) {
  e.printStackTrace();
  }*/
  System.err.println("source is " + source);
}
If I switch the comments and run the manual resource lookup, it works fine.
Should the @Resource annotation work like this, when used in a contextInitalized method?
Appserver is WAS 7.0.0.5, if it should work then I guess it's a bug? Can anyone confirm?
© Stack Overflow or respective owner