JNDI @Resource annotation

2019-08-09 09:35发布

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;
}

2条回答
来,给爷笑一个
2楼-- · 2019-08-09 10:06

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");
}
查看更多
\"骚年 ilove
3楼-- · 2019-08-09 10:10

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

查看更多
登录 后发表回答