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