JNDI @Resource annotation

我是研究僧i 提交于 2019-12-11 06:07:12

问题


In servlet and filter classes i can initialize DataSource variable via annotation

 @Resource(name = "jdbc/testDB")
    protected DataSource ds;

But how it initialize in basic class via annotation? Usually thorows NullPointerException

public class AddAuto {
        @Resource(name = "jdbc/testDB")
        private DataSource ds;
}

回答1:


What is your container?

If it's tomcat, the resource name should be something like this

@Resource(name = "java:/comp/env/jdbc/testDB")
    protected DataSource ds;

I don't know about the other container, but JBoss would be same as Tomcat, and GlassFish as your value.

Also I suggest old lookup which help you so much for debugging

void init(){
DataSource ds=(DataSource)InitialContext.doLookup("java:/comp/env/jdbc/testDB");
}



回答2:


Container inspects annotation only inside well-known componets like servlets, filters. You should transform your class to some component:

  • Web component (servlet, filters, web container listeners)
  • EJB (not supported by tomcat)
  • CDI beans

Or you can use non Java EE solution like spring



来源:https://stackoverflow.com/questions/32139617/jndi-resource-annotation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!