开发者

@Resource annotated member not injected - bad code or bug?

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 sw开发者_运维百科itch 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?


Darn it. Bug.

Webcontainer code is initializing the servlet before injection targets are retrieved from the injection engine. As a result, if servlet initialization is dependent upon an injected resource, problems can occur.

So as contextInitialized is called before any servlets can be loaded, the same problem must apply.


Another thing to consider is that resource injection will only work on objects that are created by the container, so even if the resources were already there in your contextInitialized call, this wouldn't work, because it is your code that creates the ResourceListenerTargetTest instance, WAS wouldn't know that you intend it to inject resources.

Or at least I hopes it doesn't. Otherwise, the WAS JVM would have to intercept every single object creation and make sure that the particular object doesn't need injection which would be detrimental to performance.

A similar/related principle applies in AOP, when calling a method on an object that is proxied from within the object, the method call is not intercepted (if that makes sense).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜