简体   繁体   中英

How to use @Resource annotation in servlet (or in any other Java class)?

I am experimenting with Java Dependency Injection. Many questions here on SO talk about jndi resources being wired. But I think, a java class can be wired using @Resource annotation. I have a simple servlet in which I have two properties to be wired using CDI. I am using Tomcat6, Servlet 2.5, and Weld configuration.

The servlet code:

@Inject
private HikariConnectionProperties hikariConnectionProperties;

@Resource(name = "connectionProvider")
private IConnectionProvider connectionProvider;

However I get the code compiled, deployed. But, when there is a request for the corresponding servlet I get javax.naming.NameNotFoundException: Name connectionProvider is not bound in this Context .

But, I have @Named annotation for the ConnectionProvider class. The same configuration works with @Inject for both the fields.

So, my first question is how can I fix this issue? And is there any way that I can specify scope for a particular injection(using only annotations of JSR) without using Spring's @Scope ? Any example is a great help as I am a newbie to CDI.

@Resource only works in Tomcat when you set up a resource in your container. Here's a reference for your own sake: http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html

It expects that you're binding a JNDI entry called "connectionProvider" in Tomcat. CDI does not bind elements to JNDI, it has its own internal mapping of objects to scopes. @Inject works here as you likely have not setup a resource for this class in your resource configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM