質問

I have this simple code:

public class TestClass {

    @Resource(name="jdbc/superblog")
    DataSource dataSource;

    public void testMethod() throws SQLException {
       /* try {
            Context ctx = new InitialContext();
            dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/superblog");
        } catch (NamingException e) {
            e.printStackTrace();
        }*/
        final Connection connection = dataSource.getConnection();
    }
} 

So if I use the code with the try / catch block, it works.. ( If I comment the @Resource annotation. )

However code above as it is will not work, because dataSource will be null.

How can I make the @Resource annotation work? I tried both Tomcat 6 and 7, no difference.

役に立ちましたか?

解決

How can I make the @Resource annotation work?

You must add the @Resource annotation to a servlet, filter or other supported class. The servlet 3.0 specification states that containers are not required to perform annotation injection on classes that do not implement any of the following interfaces.

javax.servlet.Servlet
javax.servlet.Filter
javax.servlet.ServletContextListener
javax.servlet.ServletContextAttributeListener 
javax.servlet.ServletRequestListener
javax.servlet.ServletRequestAttributeListener
javax.servlet.http.HttpSessionListener
javax.servlet.http.HttpSessionAttributeListener
javax.servlet.AsyncListener

Since your test class does not implement any of these interfaces I would not expect resource injection to work.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top