Search This Blog

Wednesday, May 4, 2016

Jersey + Spring integration example

This tutorial show you how to integrate Jersey web application with Spring framework.
Technologies used :
  1. Jersey 1.8
  2. Spring 3.0.5.RELEASE
  3. Eclipse 3.6
  4. Maven 3

1. Project Dependency

Declares Jersey 1.8, Spring3 and “jersey-spring.jar” dependencies in Maven pom.xml file.
Note
In “jersey-spring.jar” version, it will download all the Spring 2.5.6 dependencies. To use Spring 3, you need to exclude those old Spring libraries manually.
Markup
 <repositories>
  <repository>
   <id>maven2-repository.java.net</id>
   <name>Java.net Repository for Maven</name>
   <url>http://download.java.net/maven/2/</url>
  </repository>
 </repositories>

 <dependencies>

  
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-server</artifactId>
   <version>1.8</version>
  </dependency>

  
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>3.0.5.RELEASE</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>3.0.5.RELEASE</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>3.0.5.RELEASE</version>
  </dependency>

  
  <dependency>
   <groupId>com.sun.jersey.contribs</groupId>
   <artifactId>jersey-spring</artifactId>
   <version>1.8</version>
   <exclusions>
    <exclusion>
     <groupId>org.springframework</groupId>
     <artifactId>spring</artifactId>
    </exclusion>
    <exclusion>
     <groupId>org.springframework</groupId>
     <artifactId>spring-core</artifactId>
    </exclusion>
    <exclusion>
     <groupId>org.springframework</groupId>
     <artifactId>spring-web</artifactId>
    </exclusion>
    <exclusion>
     <groupId>org.springframework</groupId>
     <artifactId>spring-beans</artifactId>
    </exclusion>
    <exclusion>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
    </exclusion>
   </exclusions>
  </dependency>
 
 </dependencies>

2. Spring Bean

A simple “transactionBo” bean is registered in Spring Ioc container. Later you will inject this bean into Jersey service.
Java
package com.nitin.transaction;
 
public interface TransactionBo{
 
 String save();
 
}
Java
package com.nitin.transaction.impl;

import com.nitin.transaction.TransactionBo;

public class TransactionBoImpl implements TransactionBo {

 public String save() {

  return "Jersey + Spring example";

 }

}
File : applicationContext.xml – Register bean and enable the component auto scanning feature.
Markup
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
 <context:component-scan base-package="com.nitin.rest" />
 
        <bean id="transactionBo" 
                  class="com.nitin.transaction.impl.TransactionBoImpl" />
 
</beans>

3. Jersey

In REST method, you can to auto inject the “transactionBo” bean from Spring into Jersey.
Java
package com.nitin.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.nitin.transaction.TransactionBo;

@Component
@Path("/payment")
public class PaymentService {

 @Autowired
 TransactionBo transactionBo;

 @GET
 @Path("/nitin")
 public Response savePayment() {

  String result = transactionBo.save();

  return Response.status(200).entity(result).build();

 }

}

4. Integrate Jersey with Spring

The core integration is in web.xml
  1. Register Spring “ContextLoaderListener” listener class
  2. Change Jersey servlet from “com.sun.jersey.spi.container.servlet.ServletContainer” to “com.sun.jersey.spi.spring.container.servlet.SpringServlet“.
File : web.xml
Markup
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <display-name>Restful Web Application</display-name>

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
 </context-param>

 <listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>

 <servlet>
  <servlet-name>jersey-serlvet</servlet-name>
  <servlet-class>
   com.sun.jersey.spi.spring.container.servlet.SpringServlet
  </servlet-class>
  <init-param>
   <param-name>
                                 com.sun.jersey.config.property.packages
                        </param-name>
   <param-value>com.nitin.rest</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>jersey-serlvet</servlet-name>
  <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>

</web-app>

Monday, May 2, 2016

Spring @Component, @Repository, @Service and @Controller Annotations

As we know about @Autowiredannotation that it handles only wiring. You still have to define the beans themselves so the container is aware of them and can inject them for you. But with @Component, @Repository,@Service and @Controller annotations in place and after enabling automatic component scanning, spring will automatically import the beans into the container so you don’t have to define them explicitly with XML. These annotations are called Stereotype annotations as well.
Before jumping to example use of these annotations, let’s learn quick facts about these annotations which will help you in making a better decision about when to use which annotation.

@Component, @Repository, @Service and @Controller annotations

1) The @Component annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and pull it into the application context. To use this annotation, apply it over class as below:
@Component
public class EmployeeDAOImpl implements EmployeeDAO {
    ...
}
2) Although above use of @Component is good enough but you can use more suitable annotation that provides additional benefits specifically for DAOs i.e. @Repository annotation. The @Repository annotation is a specialization of the @Component annotation with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.
3) The @Service annotation is also a specialization of the component annotation. It doesn’t currently provide any additional behavior over the @Component annotation, but it’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.
4) @Controller annotation marks a class as a Spring Web MVC controller. It too is a @Component specialization, so beans marked with it are automatically imported into the DI container. When you add the @Controllerannotation to a class, you can use another annotation i.e. @RequestMapping; to map URLs to instance methods of a class.
In real life, you will face very rare situations where you will need to use @Component annotation. Most of the time, you will using @Repository, @Service and @Controller annotations. @Componentshould be used when your class does not fall into either of three categories i.e. controller, manager and dao.
If you want to define name of the bean with which they will be registered in DI container, you can pass the name in annotation itself e.g. @Service (“employeeManager”).

How to enable component scanning

Above four annotation will be scanned and configured only when they are scanned by DI container of spring framework. To enable this scanning, you will need to use “context:component-scan” tag in yourapplicationContext.xml file. e.g.
<context:component-scan base-package="com.howtodoinjava.demo.service" />
<context:component-scan base-package="com.howtodoinjava.demo.dao" />
<context:component-scan base-package="com.howtodoinjava.demo.controller" />
The context:component-scan element requires a base-package attribute, which, as its name suggests, specifies a starting point for a recursive component search. You may not want to give your top package for scanning to spring, so you should declare three component-scan elements, each with a base-packageattribute pointing to a different package.
When component-scan is declared, you no longer need to declare context:annotation-config, because autowiring is implicitly enabled when component scanning is enabled.

How to use @Component, @Repository, @Service and @Controller Annotations

As I already said that you use @Repository, @Service and @Controller annotations over DAO, manager and controller classes. But in real life, at DAO and manager layer we often have separate classes and interfaces. Interface for defining the contract, and classes for defining the implementations of contracts. Where to use these annotations? Let’s find out.
Always use these annotations over concrete classes; not over interfaces.
Once you have these stereotype annotations on beans, you can directly use bean references defined inside concrete classes. Note the references are of type interfaces. Spring DI container is smart enough to inject the correct instance in this case.
EmployeeDAO.java and EmployeeDAOImpl.java
public interface EmployeeDAO
{
    public EmployeeDTO createNewEmployee();
}
@Repository ("employeeDao")
public class EmployeeDAOImpl implements EmployeeDAO
{
    public EmployeeDTO createNewEmployee()
    {
        EmployeeDTO e = new EmployeeDTO();
        e.setId(1);
        e.setFirstName("Nitin");
        e.setLastName("Sharma");
        return e;
    }
}
EmployeeManager.java and EmployeeManagerImpl.java
public interface EmployeeManager
{
    public EmployeeDTO createNewEmployee();
}
@Service ("employeeManager")
public class EmployeeManagerImpl implements EmployeeManager
{
    @Autowired
    EmployeeDAO dao;
     
    public EmployeeDTO createNewEmployee()
    {
        return dao.createNewEmployee();
    }
}
EmployeeController.java
@Controller ("employeeController")
public class EmployeeController
{
        @Autowired
    EmployeeManager manager;
     
    public EmployeeDTO createNewEmployee()
    {
        return manager.createNewEmployee();
    }
}
EmployeeDTO.java
public class EmployeeDTO {
    private Integer id;
    private String firstName;
    private String lastName;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstName=" + firstName
                + ", lastName=" + lastName + "]";
    }
}
Let’s test the above configuration and annotations:
TestSpringContext.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.howtodoinjava.demo.service.EmployeeManager;
public class TestSpringContext
{
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //EmployeeManager manager = (EmployeeManager) context.getBean(EmployeeManager.class);
         
        //OR this will also work
         
        EmployeeController controller = (EmployeeController) context.getBean("employeeController");
         
        System.out.println(controller.createNewEmployee());
    }
}
Output:
Jan 22, 2015 6:17:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1b2b2f7f:
startup date [Thu Jan 22 18:17:57 IST 2015]; root of context hierarchy
Jan 22, 2015 6:17:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Employee [id=1, firstName=Nitin, lastName=Sharma]
Drop me a comment/query if something needs more explanation.
Happy Learning !!

My Profile

My photo
can be reached at 09916017317