@Resource 注释的成员未注入 - 错误的代码或错误?
我在 ServletContextListener 的 contextInitialized(...) 方法中实例化的类中使用 @Resource 注释,但该成员始终为 null。这是我的示例代码。
侦听器:
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);
}
如果我切换注释并运行手动资源查找,它工作正常。
在 contextInitalized 方法中使用 @Resource 注释时,是否应该像这样工作?
应用程序服务器是 WAS 7.0.0.5,如果它应该工作那么我猜这是一个错误?有人可以确认吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该死的。 错误。
因此,由于在加载任何 servlet 之前调用 contextInitialized,因此必然会出现同样的问题。
Darn it. Bug.
So as contextInitialized is called before any servlets can be loaded, the same problem must apply.
另一件需要考虑的事情是,资源注入仅适用于容器创建的对象,因此即使资源已经存在于您的 contextInitialized 调用中,这也不起作用,因为是您的代码创建了 ResourceListenerTargetTest 实例, WAS 不会知道您打算注入资源。
或者至少我希望不会。否则,WAS JVM 将必须拦截每个对象的创建,并确保特定对象不需要注入,这会损害性能。
类似/相关的原则适用于 AOP,当调用从对象内部代理的对象上的方法时,方法调用不会被拦截(如果这有意义的话)。
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).