Dependency injection with Jersey 2.0 - java

Starting from scratch without any previous Jersey 1.x knowledge, I'm having a hard time understanding how to setup dependency injection in my Jersey 2.0 project.
I also understand that HK2 is available in Jersey 2.0, but I cannot seem to find docs that help with Jersey 2.0 integration.
#ManagedBean
#Path("myresource")
public class MyResource {
#Inject
MyService myService;
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* #return String that will be returned as a text/plain response.
*/
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/getit")
public String getIt() {
return "Got it {" + myService + "}";
}
}
#Resource
#ManagedBean
public class MyService {
void serviceCall() {
System.out.print("Service calls");
}
}
pom.xml
<properties>
<jersey.version>2.0-rc1</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jax-rs-ri</artifactId>
</dependency>
</dependencies>
I can get the container to start and serve up my resource, but as soon as I add #Inject to MyService, the framework throws an exception:
SEVERE: Servlet.service() for servlet [com.noip.MyApplication] in context with path [/jaxrs] threw exception [A MultiException has 3 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MyService,parent=MyResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1039471128)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.noip.MyResource errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on com.noip.MyResource
] with root cause
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MyService,parent=MyResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1039471128)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
My starter project is available at GitHub: https://github.com/donaldjarmstrong/jaxrs

You need to define an AbstractBinder and register it in your JAX-RS application. The binder specifies how the dependency injection should create your classes.
public class MyApplicationBinder extends AbstractBinder {
#Override
protected void configure() {
bind(MyService.class).to(MyService.class);
}
}
When #Inject is detected on a parameter or field of type MyService.class it is instantiated using the class MyService. To use this binder, it need to be registered with the JAX-RS application. In your web.xml, define a JAX-RS application like this:
<servlet>
<servlet-name>MyApplication</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.mypackage.MyApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyApplication</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Implement the MyApplication class (specified above in the init-param).
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(new MyApplicationBinder());
packages(true, "com.mypackage.rest");
}
}
The binder specifying dependency injection is registered in the constructor of the class, and we also tell the application where to find the REST resources (in your case, MyResource) using the packages() method call.

First just to answer a comment in the accepts answer.
"What does bind do? What if I have an interface and an implementation?"
It simply reads bind( implementation ).to( contract ). You can alternative chain .in( scope ). Default scope of PerLookup. So if you want a singleton, you can
bind( implementation ).to( contract ).in( Singleton.class );
There's also a RequestScoped available
Also, instead of bind(Class).to(Class), you can also bind(Instance).to(Class), which will be automatically be a singleton.
Adding to the accepted answer
For those trying to figure out how to register your AbstractBinder implementation in your web.xml (i.e. you're not using a ResourceConfig), it seems the binder won't be discovered through package scanning, i.e.
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
your.packages.to.scan
</param-value>
</init-param>
Or this either
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.YourBinderImpl
</param-value>
</init-param>
To get it to work, I had to implement a Feature:
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
#Provider
public class Hk2Feature implements Feature {
#Override
public boolean configure(FeatureContext context) {
context.register(new AppBinder());
return true;
}
}
The #Provider annotation should allow the Feature to be picked up by the package scanning. Or without package scanning, you can explicitly register the Feature in the web.xml
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.Hk2Feature
</param-value>
</init-param>
...
<load-on-startup>1</load-on-startup>
</servlet>
See Also:
Custom Method Parameter Injection with Jersey
How to inject an object into jersey request context?
How do I properly configure an EntityManager in a jersey / hk2 application?
Request Scoped Injection into Singletons
and for general information from the Jersey documentation
Custom Injection and Lifecycle Management
UPDATE
Factories
Aside from the basic binding in the accepted answer, you also have factories, where you can have more complex creation logic, and also have access to request context information. For example
public class MyServiceFactory implements Factory<MyService> {
#Context
private HttpHeaders headers;
#Override
public MyService provide() {
return new MyService(headers.getHeaderString("X-Header"));
}
#Override
public void dispose(MyService service) { /* noop */ }
}
register(new AbstractBinder() {
#Override
public void configure() {
bindFactory(MyServiceFactory.class).to(MyService.class)
.in(RequestScoped.class);
}
});
Then you can inject MyService into your resource class.

The selected answer dates from a while back. It is not practical to declare every binding in a custom HK2 binder.
I'm using Tomcat and I just had to add one dependency. Even though it was designed for Glassfish it fits perfectly into other containers.
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>${jersey.version}</version>
</dependency>
Make sure your container is properly configured too (see the documentation).

Late but I hope this helps someone.
I have my JAX RS defined like this:
#Path("/examplepath")
#RequestScoped //this make the diference
public class ExampleResource {
Then, in my code finally I can inject:
#Inject
SomeManagedBean bean;
In my case, the SomeManagedBean is an ApplicationScoped bean.
Hope this helps to anyone.

Oracle recommends to add the #Path annotation to all types to be injected when combining JAX-RS with CDI:
http://docs.oracle.com/javaee/7/tutorial/jaxrs-advanced004.htm
Though this is far from perfect (e.g. you will get warning from Jersey on startup), I decided to take this route, which saves me from maintaining all supported types within a binder.
Example:
#Singleton
#Path("singleton-configuration-service")
public class ConfigurationService {
..
}
#Path("my-path")
class MyProvider {
#Inject ConfigurationService _configuration;
#GET
public Object get() {..}
}

If you prefer to use Guice and you don't want to declare all the bindings, you can also try this adapter:
guice-bridge-jit-injector

For me it works without the AbstractBinder if I include the following dependencies in my web application (running on Tomcat 8.5, Jersey 2.27):
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.cdi</groupId>
<artifactId>jersey-cdi1x</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey-version}</version>
</dependency>
It works with CDI 1.2 / CDI 2.0 for me (using Weld 2 / 3 respectively).

Dependency required for jersey restful service and Tomcat is the server.
where ${jersey.version} is 2.29.1
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
</dependency>
The basic code will be as follows:
#RequestScoped
#Path("test")
public class RESTEndpoint {
#GET
public String getMessage() {

Related

Jersey dependency injection with instance [duplicate]

Starting from scratch without any previous Jersey 1.x knowledge, I'm having a hard time understanding how to setup dependency injection in my Jersey 2.0 project.
I also understand that HK2 is available in Jersey 2.0, but I cannot seem to find docs that help with Jersey 2.0 integration.
#ManagedBean
#Path("myresource")
public class MyResource {
#Inject
MyService myService;
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* #return String that will be returned as a text/plain response.
*/
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/getit")
public String getIt() {
return "Got it {" + myService + "}";
}
}
#Resource
#ManagedBean
public class MyService {
void serviceCall() {
System.out.print("Service calls");
}
}
pom.xml
<properties>
<jersey.version>2.0-rc1</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jax-rs-ri</artifactId>
</dependency>
</dependencies>
I can get the container to start and serve up my resource, but as soon as I add #Inject to MyService, the framework throws an exception:
SEVERE: Servlet.service() for servlet [com.noip.MyApplication] in context with path [/jaxrs] threw exception [A MultiException has 3 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MyService,parent=MyResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1039471128)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.noip.MyResource errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on com.noip.MyResource
] with root cause
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MyService,parent=MyResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1039471128)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
My starter project is available at GitHub: https://github.com/donaldjarmstrong/jaxrs
You need to define an AbstractBinder and register it in your JAX-RS application. The binder specifies how the dependency injection should create your classes.
public class MyApplicationBinder extends AbstractBinder {
#Override
protected void configure() {
bind(MyService.class).to(MyService.class);
}
}
When #Inject is detected on a parameter or field of type MyService.class it is instantiated using the class MyService. To use this binder, it need to be registered with the JAX-RS application. In your web.xml, define a JAX-RS application like this:
<servlet>
<servlet-name>MyApplication</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.mypackage.MyApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyApplication</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Implement the MyApplication class (specified above in the init-param).
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(new MyApplicationBinder());
packages(true, "com.mypackage.rest");
}
}
The binder specifying dependency injection is registered in the constructor of the class, and we also tell the application where to find the REST resources (in your case, MyResource) using the packages() method call.
First just to answer a comment in the accepts answer.
"What does bind do? What if I have an interface and an implementation?"
It simply reads bind( implementation ).to( contract ). You can alternative chain .in( scope ). Default scope of PerLookup. So if you want a singleton, you can
bind( implementation ).to( contract ).in( Singleton.class );
There's also a RequestScoped available
Also, instead of bind(Class).to(Class), you can also bind(Instance).to(Class), which will be automatically be a singleton.
Adding to the accepted answer
For those trying to figure out how to register your AbstractBinder implementation in your web.xml (i.e. you're not using a ResourceConfig), it seems the binder won't be discovered through package scanning, i.e.
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
your.packages.to.scan
</param-value>
</init-param>
Or this either
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.YourBinderImpl
</param-value>
</init-param>
To get it to work, I had to implement a Feature:
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
#Provider
public class Hk2Feature implements Feature {
#Override
public boolean configure(FeatureContext context) {
context.register(new AppBinder());
return true;
}
}
The #Provider annotation should allow the Feature to be picked up by the package scanning. Or without package scanning, you can explicitly register the Feature in the web.xml
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.Hk2Feature
</param-value>
</init-param>
...
<load-on-startup>1</load-on-startup>
</servlet>
See Also:
Custom Method Parameter Injection with Jersey
How to inject an object into jersey request context?
How do I properly configure an EntityManager in a jersey / hk2 application?
Request Scoped Injection into Singletons
and for general information from the Jersey documentation
Custom Injection and Lifecycle Management
UPDATE
Factories
Aside from the basic binding in the accepted answer, you also have factories, where you can have more complex creation logic, and also have access to request context information. For example
public class MyServiceFactory implements Factory<MyService> {
#Context
private HttpHeaders headers;
#Override
public MyService provide() {
return new MyService(headers.getHeaderString("X-Header"));
}
#Override
public void dispose(MyService service) { /* noop */ }
}
register(new AbstractBinder() {
#Override
public void configure() {
bindFactory(MyServiceFactory.class).to(MyService.class)
.in(RequestScoped.class);
}
});
Then you can inject MyService into your resource class.
The selected answer dates from a while back. It is not practical to declare every binding in a custom HK2 binder.
I'm using Tomcat and I just had to add one dependency. Even though it was designed for Glassfish it fits perfectly into other containers.
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>${jersey.version}</version>
</dependency>
Make sure your container is properly configured too (see the documentation).
Late but I hope this helps someone.
I have my JAX RS defined like this:
#Path("/examplepath")
#RequestScoped //this make the diference
public class ExampleResource {
Then, in my code finally I can inject:
#Inject
SomeManagedBean bean;
In my case, the SomeManagedBean is an ApplicationScoped bean.
Hope this helps to anyone.
Oracle recommends to add the #Path annotation to all types to be injected when combining JAX-RS with CDI:
http://docs.oracle.com/javaee/7/tutorial/jaxrs-advanced004.htm
Though this is far from perfect (e.g. you will get warning from Jersey on startup), I decided to take this route, which saves me from maintaining all supported types within a binder.
Example:
#Singleton
#Path("singleton-configuration-service")
public class ConfigurationService {
..
}
#Path("my-path")
class MyProvider {
#Inject ConfigurationService _configuration;
#GET
public Object get() {..}
}
If you prefer to use Guice and you don't want to declare all the bindings, you can also try this adapter:
guice-bridge-jit-injector
For me it works without the AbstractBinder if I include the following dependencies in my web application (running on Tomcat 8.5, Jersey 2.27):
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.cdi</groupId>
<artifactId>jersey-cdi1x</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey-version}</version>
</dependency>
It works with CDI 1.2 / CDI 2.0 for me (using Weld 2 / 3 respectively).
Dependency required for jersey restful service and Tomcat is the server.
where ${jersey.version} is 2.29.1
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
</dependency>
The basic code will be as follows:
#RequestScoped
#Path("test")
public class RESTEndpoint {
#GET
public String getMessage() {

Migrated to jersey 2.x and now I get servlet container exception

So I'm building a small rest api with java using Jersey 2.23.2. I have run into a problem however, I am not able to specify the servlet in the web.xml file properly. This is how my files look like:
pom.xml
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.23.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.23.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
web.xml
...
<servlet>
<servlet-name>WebService</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>api-mashup-api.API</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>WebService</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
API.java
package api;
#Path("/v1")
public class API {
private Controller controller;
public API(){
controller = new Controller();
}
#GET
#Produces(MediaType.TEXT_HTML)
public String print1() {
return "Please specify what resource you need.";
}
/**
* Prints to the screen if we are in /v1/foo
*
* #return
*/
#GET
#Path("/foobar")
#Produces(MediaType.TEXT_HTML)
public String print2() {
return "Please specify what resource you need.";
}
}
My project folder structure looks like this:
api-mashup-api/Java Resources/src/api/API.java
I used Jersey 1.x before and then I migrated to 2.x and now I'm not sure what to put into the params of the servlet in web.xml. When I try to run the API.java on my tomcat server I get the following exception:
SEVERE: Servlet [WebService] in web application [/api-mashup-api] threw load() exception
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
I can reach my index.html just fine though, so the server works, but not the API part. Not sure what to do here. Obviously something is wrong with the servlet part.
EDIT-Things I have tried:
Added API.java to the param-valye in the web.xml
Looked at Basic full configuration for Jersey on Tomcat in eclipse
And implemented the solution. Now when running the api, the server won't crash, but I can't find any resource with http://localhost:8080/api-mashup-api/v1 for example.
Removed scope tag from the glassfish servlet container dependency.
I've had and fixed this error many times. It's basically always a dependency issue.
Here are the steps to fix it:
Make sure you're using the most recent version of all packages (i.e. 2.23.2 of glassfish) and servers, updating your POM accordingly. This is very important for your case since you're using the new version of Jersey.
Refresh your project
Use the Maven menu to clean and build
Use the Maven menu to refresh (this is different from the project refresh)
Don't skip steps or assume that if you've done some of them here and there in the past that it's the same as doing them one after the other.
Probably issue with servlet container "jersey-container-servlet-core" is for servlet 2.x containers, try changing to
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.23.2</version>
<scope>provided</scope>
</dependency>

How to inject an object into a JAX-RS resource (Jersey 2.0) [duplicate]

Starting from scratch without any previous Jersey 1.x knowledge, I'm having a hard time understanding how to setup dependency injection in my Jersey 2.0 project.
I also understand that HK2 is available in Jersey 2.0, but I cannot seem to find docs that help with Jersey 2.0 integration.
#ManagedBean
#Path("myresource")
public class MyResource {
#Inject
MyService myService;
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* #return String that will be returned as a text/plain response.
*/
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/getit")
public String getIt() {
return "Got it {" + myService + "}";
}
}
#Resource
#ManagedBean
public class MyService {
void serviceCall() {
System.out.print("Service calls");
}
}
pom.xml
<properties>
<jersey.version>2.0-rc1</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jax-rs-ri</artifactId>
</dependency>
</dependencies>
I can get the container to start and serve up my resource, but as soon as I add #Inject to MyService, the framework throws an exception:
SEVERE: Servlet.service() for servlet [com.noip.MyApplication] in context with path [/jaxrs] threw exception [A MultiException has 3 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MyService,parent=MyResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1039471128)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.noip.MyResource errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on com.noip.MyResource
] with root cause
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MyService,parent=MyResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1039471128)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
My starter project is available at GitHub: https://github.com/donaldjarmstrong/jaxrs
You need to define an AbstractBinder and register it in your JAX-RS application. The binder specifies how the dependency injection should create your classes.
public class MyApplicationBinder extends AbstractBinder {
#Override
protected void configure() {
bind(MyService.class).to(MyService.class);
}
}
When #Inject is detected on a parameter or field of type MyService.class it is instantiated using the class MyService. To use this binder, it need to be registered with the JAX-RS application. In your web.xml, define a JAX-RS application like this:
<servlet>
<servlet-name>MyApplication</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.mypackage.MyApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyApplication</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Implement the MyApplication class (specified above in the init-param).
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(new MyApplicationBinder());
packages(true, "com.mypackage.rest");
}
}
The binder specifying dependency injection is registered in the constructor of the class, and we also tell the application where to find the REST resources (in your case, MyResource) using the packages() method call.
First just to answer a comment in the accepts answer.
"What does bind do? What if I have an interface and an implementation?"
It simply reads bind( implementation ).to( contract ). You can alternative chain .in( scope ). Default scope of PerLookup. So if you want a singleton, you can
bind( implementation ).to( contract ).in( Singleton.class );
There's also a RequestScoped available
Also, instead of bind(Class).to(Class), you can also bind(Instance).to(Class), which will be automatically be a singleton.
Adding to the accepted answer
For those trying to figure out how to register your AbstractBinder implementation in your web.xml (i.e. you're not using a ResourceConfig), it seems the binder won't be discovered through package scanning, i.e.
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
your.packages.to.scan
</param-value>
</init-param>
Or this either
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.YourBinderImpl
</param-value>
</init-param>
To get it to work, I had to implement a Feature:
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
#Provider
public class Hk2Feature implements Feature {
#Override
public boolean configure(FeatureContext context) {
context.register(new AppBinder());
return true;
}
}
The #Provider annotation should allow the Feature to be picked up by the package scanning. Or without package scanning, you can explicitly register the Feature in the web.xml
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.Hk2Feature
</param-value>
</init-param>
...
<load-on-startup>1</load-on-startup>
</servlet>
See Also:
Custom Method Parameter Injection with Jersey
How to inject an object into jersey request context?
How do I properly configure an EntityManager in a jersey / hk2 application?
Request Scoped Injection into Singletons
and for general information from the Jersey documentation
Custom Injection and Lifecycle Management
UPDATE
Factories
Aside from the basic binding in the accepted answer, you also have factories, where you can have more complex creation logic, and also have access to request context information. For example
public class MyServiceFactory implements Factory<MyService> {
#Context
private HttpHeaders headers;
#Override
public MyService provide() {
return new MyService(headers.getHeaderString("X-Header"));
}
#Override
public void dispose(MyService service) { /* noop */ }
}
register(new AbstractBinder() {
#Override
public void configure() {
bindFactory(MyServiceFactory.class).to(MyService.class)
.in(RequestScoped.class);
}
});
Then you can inject MyService into your resource class.
The selected answer dates from a while back. It is not practical to declare every binding in a custom HK2 binder.
I'm using Tomcat and I just had to add one dependency. Even though it was designed for Glassfish it fits perfectly into other containers.
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>${jersey.version}</version>
</dependency>
Make sure your container is properly configured too (see the documentation).
Late but I hope this helps someone.
I have my JAX RS defined like this:
#Path("/examplepath")
#RequestScoped //this make the diference
public class ExampleResource {
Then, in my code finally I can inject:
#Inject
SomeManagedBean bean;
In my case, the SomeManagedBean is an ApplicationScoped bean.
Hope this helps to anyone.
Oracle recommends to add the #Path annotation to all types to be injected when combining JAX-RS with CDI:
http://docs.oracle.com/javaee/7/tutorial/jaxrs-advanced004.htm
Though this is far from perfect (e.g. you will get warning from Jersey on startup), I decided to take this route, which saves me from maintaining all supported types within a binder.
Example:
#Singleton
#Path("singleton-configuration-service")
public class ConfigurationService {
..
}
#Path("my-path")
class MyProvider {
#Inject ConfigurationService _configuration;
#GET
public Object get() {..}
}
If you prefer to use Guice and you don't want to declare all the bindings, you can also try this adapter:
guice-bridge-jit-injector
For me it works without the AbstractBinder if I include the following dependencies in my web application (running on Tomcat 8.5, Jersey 2.27):
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.cdi</groupId>
<artifactId>jersey-cdi1x</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey-version}</version>
</dependency>
It works with CDI 1.2 / CDI 2.0 for me (using Weld 2 / 3 respectively).
Dependency required for jersey restful service and Tomcat is the server.
where ${jersey.version} is 2.29.1
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
</dependency>
The basic code will be as follows:
#RequestScoped
#Path("test")
public class RESTEndpoint {
#GET
public String getMessage() {

Integrating Jetty with JAX-RS-Jersey

After an exhaustive search of the web and Stackoverflow, I am still stuck with trying to figure out how to integrate a RESTlet style interface provided by Jersey with Jetty.
I have my Jetty server up and running and as such Jersey seems pretty easy to use as well, does anyone know how to tie the two together? Any concrete links would help — I am a little new to servlet programming as well.
I created an app using Jetty and Jersey a while back. It's just a standard webapp really:
web.xml:
<servlet>
<servlet-name>rest.service</servlet-name>
<servlet-class>
com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
<param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>your.package.with.jersey.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest.service</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
A rest resource:
package your.package.with.jersey.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
#Path("login")
public class LoginResource {
#Context
private SecurityContext security;
#GET
#Produces(MediaType.APPLICATION_XML)
public String login() {
String email = security.getUserPrincipal().getName();
return "ok";
}
}
Jetty starter:
public class StartJetty {
public static void main(String[] args) throws Exception {
Server server = new Server();
SocketConnector connector = new SocketConnector();
// Set some timeout options to make debugging easier.
connector.setMaxIdleTime(1000 * 60 * 60);
connector.setSoLingerTime(-1);
connector.setPort(8080);
server.setConnectors(new Connector[] { connector });
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/");
bb.setWar("src/main/webapp");
server.addHandler(bb);
try {
System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
server.start();
while (System.in.available() == 0) {
Thread.sleep(5000);
}
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
}
pom.xml:
<!-- Jetty -->
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-util</artifactId>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-management</artifactId>
</dependency>
<!-- Jersey (JAX-RS) -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-test-framework</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.grizzly</groupId>
<artifactId>grizzly-servlet-webserver</artifactId>
</dependency>
(...)
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
</plugin>
Hope these snippets point you in the right direction.
You might want to look at Dropwizard for out-of-the-box integration between Jetty, Jersey, Jackson, Logback/Log4j/JUL/CJL and JDBI, all nicely instrumented with Yammer Metrics.

#Startup annotation does not work

I use the #Startup annotation to set entry point on the deploying process in EJB, but it does not work. See code example below:
#Singleton
#Startup
public class SchedulerManager {
private static Logger log = Logger.getLogger(SchedulerManager.class);
#PostConstruct
public void atStartup() {
System.out.println("stutrup!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
I'm using JBoss5.1.0
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
Please, give me suggestion what I'm doing wrong.
Thanks!
Artem
The #Startup annotation is part of ejb 3.1 / jee6 while jboss 5 only implements jee5. You would have to switch to jboss 6 to use it.
Edit: An alternative might be to implement the contextInitialized method of a ServletContextListener, which can be declared in web.xml like this:
<listener>
<listener-class>package.ListenerClassName</listener-class>
</listener>

Categories

Resources