简体   繁体   中英

Injection of HttpServletRequest

I am using ejb 3 and trying to @Inject HttpServletRequest, but while deploying I occur exception.

Code:

@Inject private HttpServletRequest httpRequest;

Exception:

org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [HttpServletRequest] with qualifiers [@Default] at injection point [[field] @Inject private com.kmware.ttk.highway.beans.session.UserSessionBean.httpRequest]

What could I do with that?

The lifecycle of HttpServletRequest is managed by the EJB/web container, not the CDI container. Attempting to inject it leads to issues because there are typically many implementations of the interface,and your CDI container does not have enough information to make a decision on which implementation to inject. Even if you successfully injected an instance of it, it would not be the same instance as being managed by the EJB container.

To acquire a properly managed instance of the request, do this instead:

@Context
private HttpServletRequest httpRequest;

If your dependent is a JAX-RS (Restful) class then note the answer above. On the other hand, if you've got a more complex arrangement of dependency injection the question is certainly valid.

This capability has been added to the CDI 1.1 specification (JSR-346) which in turn has been added to the new Java EE 7 specification. In other words, the newest class of Java Enterprise Application servers will be able to handle this.

In the meantime, if you need to be able to manage some request scopes dependencies that in term need access to the actual HttpServletRequest information, you can use your approach and use the JBoss Solder tool. (Don't panic if the web site looks defunct, the fact of the matter is the work got shifted to the official CDI 1.1 spec implementation—ie "Weld 2"—so they aren't working on solder any more. But it's still perfectly suitable for CDI 1.0.)

The maven dependencies would be

<dependency>
  <groupId>org.jboss.solder</groupId>
  <artifactId>solder-api</artifactId>
  <version>3.2.0.Final</version>
  <type>jar</type>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.jboss.solder</groupId>
  <artifactId>solder-impl</artifactId>
  <version>3.2.0.Final</version>
  <type>jar</type>
  <scope>compile</scope>
</dependency>

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