[JAX-RS] Using CDI for dependency injection in JAX-RS

1. The resource class

package com.example.jaxrs;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
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.HttpHeaders;
import javax.ws.rs.core.MediaType;
@Path("cdiexample")
@RequestScoped
public class StringResource {
	@Inject
	private MyService service;
	public StringResource() {
	}
	@Context
	private HttpHeaders httpHeaders;
	@PostConstruct
	private void postCons() {
	}
	@Produces(MediaType.TEXT_PLAIN)
	@GET
	public String get() {
		return service.getMessage();
	}
}

2. MyService interface

package com.example.jaxrs;
public interface MyService {
	public String getMessage();
}

3. MyServiceImpl

package com.example.jaxrs;
public class MyServiceImpl implements MyService{
	@Override
	public String getMessage() {
		return "THIS IS THE MESSAGE";
	}
}

4. web.xml (under /WEB-INF/)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
		 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">
	<servlet>
		<servlet-name>javax.ws.rs.core.Application</servlet-name>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>javax.ws.rs.core.Application</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>

5. beans.xml (under /WEB-INF/)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/
XMLSchema-instance" xsi:schemeLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/beans_1_0.xsd">
<!-- This is empty on purpose. -->
</beans>

6. Deploy on glassfish! and access it: http://localhost:8080/TestCDI/rest/cdiexample (given that the project name is TestCDI).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s