简体   繁体   English

如何在servlet(或任何其他Java类)中使用@Resource批注?

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

I am experimenting with Java Dependency Injection. 我正在尝试Java依赖注入。 Many questions here on SO talk about jndi resources being wired. 关于SO的许多问题都在谈论关于连接的jndi资源。 But I think, a java class can be wired using @Resource annotation. 但我认为,可以使用@Resource注释连接Java类。 I have a simple servlet in which I have two properties to be wired using CDI. 我有一个简单的servlet,其中有两个要使用CDI连接的属性。 I am using Tomcat6, Servlet 2.5, and Weld configuration. 我正在使用Tomcat6,Servlet 2.5和Weld配置。

The servlet code: Servlet代码:

@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 . 但是,当请求相应的servlet时,我得到javax.naming.NameNotFoundException: Name connectionProvider is not bound in this Context

But, I have @Named annotation for the ConnectionProvider class. 但是,我为ConnectionProvider类提供了@Named注释。 The same configuration works with @Inject for both the fields. 对于两个字段,@ @Inject使用相同的配置。

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 ? 而且有什么方法可以指定特定注入的范围(仅使用JSR的注释)而无需使用Spring的@Scope Any example is a great help as I am a newbie to CDI. 因为我是CDI的新手,所以任何例子都对我有很大的帮助。

@Resource only works in Tomcat when you set up a resource in your container. @Resource仅在您在容器中设置资源时才在Tomcat中工作。 Here's a reference for your own sake: http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html 这是为您自己的参考: 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. 它期望您在Tomcat中绑定一个名为“ connectionProvider”的JNDI条目。 CDI does not bind elements to JNDI, it has its own internal mapping of objects to scopes. CDI不会将元素绑定到JNDI,它具有自己的对象到范围的内部映射。 @Inject works here as you likely have not setup a resource for this class in your resource configuration. @Inject在这里起作用,因为您可能尚未在资源配置中为此类设置资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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