Java Collection Framework

Collection is a group of seperate objects represented as a single unit and collection framework is an architecture for representing and manipulating the collections.

Collection framework defines several interfaces,d Few of them are :

  • Collection Interface
  • List Interface
  • Set Interface
  • Queue Interface

Map Interface(though not exactly part of framework)

Few of the methods declared in the collection interface and overriden by the child classes

S.NoMethodUsage
1public boolean add(E e), addAll(Collection<? extends E> c)It is used to insert an element in this collection, the other is used to Insert one collection into another.
2public boolean remove(Object element), removeAll(Collection<?> c)used to delete an element, other is used to delete all elements of the collection
3public int size()returns total number of elements in the collection
4public boolean contains(Object element)used to search an element in the collection
5public int size()returns total number of elements in the collection
6public Iterator iterator()returns an iterator
7public boolean isEmpty()check collection for empty
8public int hashCode()returns hashcode of the collection

Iterable Interface

Few of the methods declared in the collection interface and overriden by the child classes

The Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface.

It has only one abstract method:

 Iterator iterator() : 

and returns the iterator over the elements of type T.


Difference between @Controller and @RestController annotation

Spring’s @Controller and @RestController Annotations

Controller : In Spring the incoming request are handled by the controllers, in terms of a web based application it is the servlet which is responsible for identifying a correct controller url.

S.No@Controller@RestController
1Typically used in spring mvc applicationsTypically Used in RESTful Web Services/AJAX calls which demand response in specific format like(eg: json, xml).
2It is just @Controller , response body need to be added explicitly.It is a combination of @Controller + @ResponseBody,
It does the job in single statement.
3It typically sends data to a view resolver in html format and is used with technologies like the JSP or FTL.
To send response to REST based or AJAX calls @ResponseBody annotation is used along with @Controller.
It typically sends data back to applications like REST based or AJAX calls which is actually looking for a JSON type response and does not rely on view resolvers.
In such cases use @RestController
4If you see the code within.

@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Component public @interface Controller { //….. }
If you see the code within.

@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { //….. }

Examples

1. @Controller – Usage in spring mvc application

@Controller
@RequestMapping("department")
public class DepartmentController
{
    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public Department getDepartmentByName(@PathVariable String name, Model model) {
  
        //pull data, set in model and then return the template
  
        return departmentTemplate;
    }
}        
        

2. @Controller + @ResponseBody in spring

@Controller
@ResponseBody
@RequestMapping("department")
public class DepartmentController
{
    @RequestMapping(value = "/{name}", method = RequestMethod.GET, 
                    produces ="application/json")
    public Department getDepartmentByName(@PathVariable String name) {
  
        //pull data, set model and then return Object model in json format
  
        return department;
    }
}
        

3. @RestController in spring

@RestController
@RequestMapping("department")
public class DepartmentController
{
    @RequestMapping(value = "/{name}", method = RequestMethod.GET, 
                    produces ="application/json")
    public Department getDepartmentByName(@PathVariable String name) {
  
        //pull data, set model and then return Object model in json format
  
        return department;
    }
}                
        

This code does the same job as in example 2 , here we use single annotation(@RestController) instead of two(@Controller, @ResponseBody).

Spring’s @RequestMapping annotation

This annotation is used to provide routing information or you can understand in a simple way it allows application to understand different apis with the help of URL, a unique URL for every api.

A sample code is here:

@RestController  
public class HomeController {  
@RequestMapping(value = "/allDepartmentNames", method = "GET")  

    public List getAllDepartmentName(){  
  //….
        return list;  
    }  
}                
        

Summary

In this spring boot annotations tutorial you have learnt about annotations and auto configuration features of spring boot. These are few of the most in use annotations which you might surely use in your spring boot application. Hope you liked it !


Spring Boot microservices

This post will make you understand the basics of microservices and its architecture.

What you get to know :

  • What is a Monolith application?
  • What is a Microservice?
  • What are the Challenges with Microservices?
  • How does Spring Boot and Spring Cloud make developing Microservices easy?

What is a Monolith Application?

If you have ever worked in a project of this sort where

  • A team is of size say more than 20 working for it
  • Application is of hundred thousands of lines of code.
  • The application has wide range of functionalities
  • Debugging is a big challenge
  • Introducing a new technology is a big challenge or nearly impossible.
  • And you release it to production one each month

Then the application has characteristics of a Monolith application.

Challenges which are faced here :

  • Scalability one of the greatest Challenges.
  • Difficulty in new Technology Adoption/introduction.
  • Adapt new Processes – like Agile?
  • Difficult to Automate Tests.
  • Difficult to Adapt to Modern Development Practices

Microservices

To overcome the challenges faced in Monolith application came the Microservices, which are scalable and easy to adapt to new technologies.

So what are Microservices ?

As defined by some experts, Developing an application as a suite of small services Each running in its own process and communicate with light weight mechanism(often as HTTP resource APIs). These services are independently deployable by automated systems and these may use independent or different data storage technologies.

So a few important characteristics which defines a microservice can be :

  • Small units which do their job and are easily deployable.
  • They communicate via HTTP REST calls or triggered event based.
  • Which are easily scalable.

Advantages of Microservices

  • New Technology & Process Adaption becomes easier. You can try new technologies with each microservice that we create.
  • Faster Release Cycles – You can adopt agile development methods, create microservices which are easy to maintain and deploy.
  • Scaling with Cloud is really simple.
  • Easy Automation Testing because of smaller units of microservices.
spring boot monolith-architecture

Vs

spring-boot-microservices-architecture-vs-monolith-architecture

Challenges in Microservice Architectures

While developing a number of smaller components might look easy, there are a number of inherent complexities that are associated with microservices architectures.

Lets look at some of the challenges:

  • Fast Setup needed : You cannot spend a month setting up each microservice. You should be able to create microservices quickly.
  • DevOps Automation : Because there are a number of smaller components instead of a monolith application, you need to automate everything – Builds, Deployment etc.
  • Monitoring & Visibility : You now have a number of smaller components to deploy and maintain. Maybe 100, 1000 or maybe more. You should be able to monitor and identify problems automatically. You need great visibility around all the components.
  • Bounded Context : Deciding the boundaries of a microservice is not an easy task. Your understanding of the domain evolves over a period of time and so does the scope of a functionality. You need to ensure that the microservice boundaries evolve.
  • Configuration Management Solution : You need to maintain configurations for hundreds of components across environments so You would need a Configuration Management solution.
  • Configuration Management Solution : You need to maintain configurations for hundreds of components across environments so You would need a Configuration Management solution.
  • Fault Tolerance : If a microservice at the bottom of the call chain fails, it can have knock on effects on all other microservices. Microservices should be fault tolerant by Design so no other service bears its impact.
  • Debugging : When there is a problem that needs investigation, you might need to look into multiple services across different components. So the Centralized Logging and Dashboards are essential to make it easy to debug problems.

Solutions to Challenges with Microservice Architectures

One Stop solution – Spring Boot

  • Provide non-functional features
  • embedded servers (easy deployment with containers)
  • metrics (for monitoring)
  • health checks (for monitoring services)
  • externalized configuration

Summary

In this spring boot microservices tutorial you have learnt about monolithic and microservices architecture, challenges of monolithic arthictecure and how microservices overcome its challenges its uses advantages.
Hope you liked it !


Spring boot actuator and its endpoints

Spring Boot Actuator is a sub-project of Spring Boot. It provides several production ready features to any spring boot application. Once it is added in any spring boot application, it exposes a number of REST endpoints to monitor your application. You can monitor your application health, version details, thread dumps, logger details, application bean details, etc. without writing any code to avail these features.

After configuring spring actuator in your project, you get around 15 built-in endpoints to manage and monitor your application by default. The list of these endpoints are provided below. In case you require more control, you can also add your own endpoints. Not only this spring actuator also provide flexibility to rename the existing REST endpoints to any custom name you want.

Creating a Spring Boot application with Actuator

Two ways to do that:

  1. Using Spring.io initializr – also select Actuator jar along with others.
  2. By creating a spring boot project and adding Actuator Dependency to it.

This annotation is basically used on the class with main method, to mark the class as the main class of the application.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
        

Where Spring boot Parent version is:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.7.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
</parent>
       

And For Gradle,

dependencies {
  compile("org.springframework.boot:spring-boot-starter-actuator")
}
        

Monitoring your application through Actuator Endpoints

EndPointsAPI DescriptionDefault Value
actuatorIt provides a hypermedia-based “discovery page” for the other endpoints. It requires Spring HATEOAS to be on the classpath.True
auditeventsIt exposes audit events information for the current application.True
autoconfigIt is used to display an auto-configuration report showing all auto-configuration candidates and the reason why they ‘were’ or ‘were not’ applied.True
beansIt is used to display a complete list of all the Spring beans in your application.True
configpropsIt is used to display a collated list of all @ConfigurationProperties.True
dumpIt is used to perform a thread dump.True
envIt is used to expose properties from Spring’s ConfigurableEnvironment.True
flywayIt is used to show any Flyway database migrations that have been applied.True
healthIt is used to show application health information.False
infoIt is used to display arbitrary application info.False
loggersIt is used to show and modify the configuration of loggers in the application.True
liquibaseIt is used to show any Liquibase database migrations that have been applied.True
MetricsIt is used to show metrics information for the current application.True
mappingsIt is used to display a collated list of all @RequestMapping paths.True
shutdownIt is used to allow the application to be gracefully shutdown.True
traceIt is used to display trace information.True

Enabling and Disabling Actuator Endpoints

By Default it Exposes 2 endpoint(s) beneath base path ‘/actuator’

You can enable or disable an actuator endpoint by setting the property management.endpoint.id. enabled to true or false (where id is the identifier for the endpoint).

For example, to enable the shutdown endpoint, add the following to your application.properties file –

management.endpoint.shutdown.enabled=true

Exposing Actuator Endpoints

To enable the rest of the 15 endpoints , add the following to you applicaiton.properties

management.endpoints.web.exposure.include=*

Or if you want to expose only specific endpoint , then add the following to properties file

management.endpoints.web.exposure.include=health,info // this will enable only health and info rest end points.

Summary

In this spring boot actuator tutorial you have learnt about actuator and the amount of apis if offers to help you monitor and manage your applications health. These features you must add and explore in your spring boot application. Hope you liked it !


Spring boot rest api example – hello world

In this section We will learn to create a spring boot hello world rest api based application just by following 5 simple steps.

Here we GO !

Step 1 : Open Spring Initializr

Open Spring Initializr and create a spring boot rest project like below snapshot. Add the REST dependency and generate the project.

spring boot initializr

Add maven dependencies, These are the two dependencies which gets added on generating the above project.

<dependencies>
- <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
- <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>
            

Spring Boot REST Controller – make a REST controller

  • @RestController Annotation used on the controller class.
  • @GetMapping & @PostMapping used to declare get and post apis.
  • Property consumes & produces used to consume and produce data of different types for example json, xml, html.

Step 2 : Create Get API

Create a class as below, copy and paste the code in you IDE.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api")
public class DepartmentController{

	@GetMapping("/hello")
	public String helloWorld() {

		return "Hello World !";

	}

	@GetMapping(path = "/dept", produces = "application/json")
	public Department getDepartment() {
		
		return new Department("Information Technology", "IT");	
	}	
}

Step 3 : Create Post API

Create a class as below, copy and paste the code in you IDE.

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api")
public class DepartmentController{

  @PostMapping(path = "/dept", produces = "application/json", 
              consumes = "application/json")
  public String  addDepartment(@RequestBody Department department) {
    
    return department.getDepCode()+"--"+department.getDepName();
    
  } 
}        

Step 4 : main method using @SpringBootApplication

Create a class with main method as below, copy and paste the code in you IDE,
key point here is we are using @SpringBootApplication annotation to notify the framework that this is our main springboot class

package com.programmer.actuator;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootprojectApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringbootprojectApplication.class, args);
  }

}         

Result

You can download a REST client or create your own and test the GET and POST apis as below.

GET API Response – When we hit the GET api see the snapshots below

spring boot initializr
spring boot initializr

POST API Response – When we hit the POST api see the snapshots below

spring boot initializr
spring boot initializr

Summary

In this section we learnt how to create a simple REST based project with SPRING BOOT. Hope you enjoyed it !


Spring Boot Annotations

Spring boot has made configuration of spring and it’s dependencies really very easy with autoconfigure feature, most of the annotations are placed in the packages below.

org.springframework.boot.autoconfigure &
org.springframework.boot.autoconfigure.condition

Below you will see a few of the most used spring boot annotations :

1. @SpringBootApplication


This annotation is basically used on the class with main method, to mark the class as the main class of the application.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
class EmployeeApplication {
  
    public static void main(String[] args) {
        SpringApplication.run(EmployeeApplication.class, args);
    }
}
        

The @SpringBootApplication annotation encapsulates @EnableAutoConfiguration, @Configuration and @ComponentScan annotations. Which enables their respective functionalities as well.

2. @SpringBootApplication


This annotation enables auto-configuration of the Spring Application Context, with the help of this annotation, spring attempts to look for beans that we are likely to add based on the presence of predefined classes in classpath.

For example, if we have embedded tomcat jar on the classpath, we are likely to want a TomcatServletWebServerFactory.

@Configuration
@EnableAutoConfiguration
@Import({ MyConfig1.class, MyConfig2.class })
public class EmployeeApplication {

  public static void main(String[] args) {
      SpringApplication.run(EmployeeApplication.class, args);
  }

}     
       

3. @Configuration


It indicates that a class provides Spring Boot application configuration.

4. @ComponentScan


Explicitly used with spring, but default in spring-boot. It scans all the Beans inside the package mentioned.

The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.

See below an example

package com.programmertoday.base;
import com.programmertoday.SampleBean;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
  
@Configuration
@ComponentScan(basePackages = {
        "com.programmertoday.samplepackage1",
        "com.programmertoday.samplepackage2",
        "com.programmertoday.samplepackage3"
    },
    basePackageClasses = SampleBean.class)
public class EmployeeApplication {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.
        run(EmployeeApplication.class, args);
        System.out.println("Contains SampleBean  : " + context.containsBeanDefinition("SampleBean"));
      }
}

package com.programmertoday.samplepackage1;
import org.springframework.stereotype.Component;
@Component("SampleBean")
public class SampleBean{
}

OUTPUT
Contains SampleBean  : true 
       

5. @AutoConfigureBefore, @AutoConfigureAfter, @AutoConfigureOrder


We can use the @AutoConfigureAfter or @AutoConfigureBefore annotations if our configuration needs to be applied in a specific order (like before after any other configuration). Write the annotation above the current Bean where you want to apply this order of application of configuration.

@Configuration
@AutoConfigureAfter(Cache1.class)
@ConditionalOnBean(CacheManager.class)
@ConditionalOnClass(CacheStatisticsProvider.class)
public class Cache2
{
    @Bean
    public SampleBean returnNewBean(){
        return new SampleBean ();
    }
}             
       

6. Condition annotations


It allows to register a bean only when the condition meets. When we write our custom auto-configurations, we want Spring to use them conditionally. We can achieve this with conditional annotations.

  1. @ConditionalOnBean and @ConditionalOnMissingBean : former means if bean is present , the latter means the if the bean is not present.
  2. @ConditionalOnClass and @ConditionalOnMissingClass : These annotations let configuration classes be included based on the presence or absence of specific classes.
  3. @ConditionalOnNotWebApplication and @ConditionalOnWebApplication : These annotations let configuration be included depending on whether the application is a “web application” or not
  4. @ConditionalOnProperty : This annotation lets configuration be included based on the presence and value of a Spring Environment property
  5. @ConditionalOnResource : This annotation lets configuration be included only when a specific resource is present in the classpath.
  6. @ConditionalOnExpression : This annotation lets configuration be included based on the result of a SpEL expression.
  7. @ConditionalOnCloudPlatform : This annotation lets configuration be included when the specified cloud platform is active.

Summary

In this spring boot annotations tutorial you have learnt about annotations and auto configuration features of spring boot. These are few of the most in use annotations which you might surely use in your spring boot application. Hope you liked it !


Spring – Transaction Management in Spring

A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency.
The concept of transactions can be described with the following four key properties described as ACID −

Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful.

Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc.

Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption.

Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure.

Summary

In this tutorial we learnt about Spring Transaction Management and the principle of ACID properties it follows.
Hope you liked it !


Spring AOP – Aspect Oriented Programming

AOP is like triggers in programming languages such as Perl, .NET, Java, and others.
Spring AOP module provides interceptors to intercept an application. For example, when a method is executed, you can add extra functionality which executes always before or after the method execution using annotations and xml configurations.
AOP involves breaking down program logic into distinct parts called concerns. Aspects enable the modularization of concerns that cut across multiple types and objects (often termed crosscutting concerns).
Common examples are – logging, auditing, transactions, security, caching, etc.

Given a scenario :

You have to maintain log and send notifications when methods starting with *serviceImpl are called.
One way : is to write the log statements in every serviceImpl methods
Problem : after you write the logs, if requirement comes to change the logging statment, then you need to change it in every possible method where you wrote the log statement, it leads to severe maintenance problem.
Better way : Define a concerns and use it. Even if you want to change the logs then you need to change it at only one place and not in every file.

AOP terminologies

1. Aspect : An Aspect is the concern (cross cutting concern) which you want to implement in the application such as logging, performance monitoring, transactional handing etc.

2. Advice : An Advice is the actual implementation of the aspect. Aspect is a concept and Advice is the concrete implementation of the concept.

3. Join Point : JoinPoint is a point in the execution of the program where an aspect can be applied. It could be before/after executing the method, before throwing an exception, before/after modifying an instance variable etc. Keep in mind that it is not necessary and also not required to apply an aspect at all the available join points. Spring AOP only supports method execution join points.

4. Aspect : An Aspect is the concern (cross cutting concern) which you want to implement in the application such as logging, performance monitoring, transactional handing etc.

5. Point cut : PointCuts tell on which join points the aspect will be applied. An advice is associated with a point cut expression and is applied to a join point which matches the point cut expression.

6. Target : An Aspect is the concern (cross cutting concern) which you want to implement in the application such as logging, performance monitoring, transactional handing etc.

7. Weaving : Weaving is the process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime.

Types of Advice Spring aspects work with these advice

  • Before Advice: it executes before a join point.
  • After Returning Advice: it executes after a joint point completes normally.
  • After Throwing Advice: it executes if method exits by throwing an exception.
  • After (finally) Advice: it executes after a join point regardless of join point exit whether normally or exceptional return.
  • Around Advice: It executes before and after a join point.

Summary

In this tutorial we learnt about Spring Aspect Oriented Programming, AOP terminologies, a scenario where it can be used and types of Advice.
Hope you liked it !


Spring DI – Dependency Injection in spring

It is the heart of spring framework, it facilitates the idea of keeping classes independent of each other and injecting them wherever required. DI helps decouple your application objects from each other.

Spring framework provides two ways to inject dependency

1. By Constructor
2. By Setter method

1. By Constructor Injection

It is achieved when the container invokes the target constructor with the number of arguments. Below is an example where a class is injected to another via constructor by passing the reference as constructor arguments.


/********Mobile class*********/
public class Mobile {
    private Recharge recharge;
    
    public Mobile(Recharge recharge) {}
      System.out.println("Inside Mobile constructor." );
      this.recharge = recharge;
    }
    public void getRecharge() {
      recharge.doRecharge();
    }
    }
}
/********Recharge class*********/			
public class Recharge {}
    public Recharge(){
      System.out.println("Inside Recharge constructor." );
    }
    }
    public void doRecharge() {
      System.out.println("Inside doRecharge." );
    }
    }
}
/********Main class*********/
public class MainApp {
    public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

    Mobile mb = (Mobile) context.getBean("mobile");
    mb.getRecharge();
    }
}

/********Beans.xml*********/
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
    xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation = "http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- Definition for Mobile bean -->
    <bean id = "mobile" class = "com.programmertoday.Mobile">
      <constructor-arg ref = "recharge"/>
    </bean>

    <!-- Definition for Recharge bean -->
    <bean id = "recharge" class = "com.programmertoday.Recharge"></bean>

</beans>

OUTPUT:
------
Inside Recharge constructor.
Inside Mobile constructor.
Inside doRecharge.

2. By Setter Injection

It is achieved when the container invokes the setter methods on your beans after calling a no-arg constructor or no-arg static factory method to instantiate your bean.

public class TextEditor {
    private SpellChecker spellChecker;

    // a setter method to inject the dependency.
    public void setSpellChecker(SpellChecker spellChecker) {
      System.out.println("Inside setSpellChecker." );
      this.spellChecker = spellChecker;
    }
    // a getter method to return spellChecker
    public SpellChecker getSpellChecker() {
      return spellChecker;
    }
    public void spellCheck() {
      spellChecker.checkSpelling();
    }
}

Difference between constructor and setter injection

FactorSI(Setter Injection)CI(Constructor Injection)
Partial dependencyCan be injected using setter injection, e.g if there is a Bean with 4 properties having 4 args constructor and setter methods, and if you want to pass value for only one property from other class its possible by setter method only.Not possible with constructor injection.
OverridingIf both the types of DI are present in a file then the SI overrides the CI.Less priority over SI
Easy ChangesNo need to create an instance of a class to change a value using setter injection.But using constructor injection one has to create a new bean instance.

Summary

In this tutorial we learnt about Spring Dependency Injection, two types of dependency injection (constructor and setter) and its difference.
Hope you liked it !


REST Jackson API Hello World REST API Example

In this article we will learn how to use JACKSON api in a jersey based rest web services project in java. Jersey uses Jackson to convert object to / form JSON. In this tutorial, we show you how to convert a “Track” object into JSON format, and return it back to user.

Tools used

Maven
JDK 1.8 (even 1.6 would work fine)
Eclipse/IntelliJ(you can use whichever you are comfortable with)
Tomcat Server 8

These steps are followed in this tutorial,

it’s Damn Easy !

Step 1: create a java web project in eclipse and convert it to maven project.
Step 2: add jersey jackson dependency in pom.xml and update the project.
Step 3: create an API class.
Step 4: in the web.xml add the servlet and servlet mapping.
Step 5: Just run the project, Hurray !

POM Dependencies

<properties>
    <jersey2.version>2.28</jersey2.version>
    <jaxrs.version>2.0.1</jaxrs.version>
</properties>

<dependencies>
  <!-- JAX-RS -->
      <dependency>
          <groupId>javax.ws.rs</groupId>
          <artifactId>javax.ws.rs-api</artifactId>
          <version>${jaxrs.version}</version>
      </dependency>
      <!-- Jersey 2.28 -->
      <dependency>
          <groupId>org.glassfish.jersey.containers</groupId>
          <artifactId>jersey-container-servlet</artifactId>
          <version>${jersey2.version}</version>
      </dependency>
      <dependency>
          <groupId>org.glassfish.jersey.core</groupId>
          <artifactId>jersey-server</artifactId>
          <version>${jersey2.version}</version>
      </dependency>
      <dependency>
          <groupId>org.glassfish.jersey.inject</groupId>
          <artifactId>jersey-hk2</artifactId>
          <version>2.28</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/
        jersey-media-json-jackson -->
      <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.28</version>
      </dependency>
</dependencies>
  

Note: What happens when you do not add jersey-media-json-jackson jar in pom.xml ? The API when hit returns a SEVERE exception:
SEVERE: MessageBodyWriter not found for media type=application/json, type=class com.programmertoday.restjersey.model.Department, genericType=class com.programmertoday.restjersey.model.Department.
Because the resource is trying to produce an object of type json, but it does not find any convertor which converts Object into a json, hence adding the above jackson jar resolves this issue.

1. API code

package com.programmertoday.restjersey.api;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/api")
public class JerseyResource {

  @GET
  @Path("/department")
  @Produces(MediaType.APPLICATION_JSON)
    public Department getDepartment()
    {
          return new Department("IT","Information Technology");
    }
}
   

2. Model Class

package com.programmertoday.restjersey.model;

public class Department {

  private String depName;
  private String depCode;

  public Department(String a, String b) {
    this.depCode = a;
    this.depName = b;
  }

  public String getDepName() {
    return depName;
  }

  public void setDepName(String depName) {
    this.depName = depName;
  }

  public String getDepCode() {
    return depCode;
  }

  public void setDepCode(String depCode) {
    this.depCode = depCode;
  }
}
    

3. Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
id="WebApp_ID" version="3.0">

<display-name>RESTful_Project</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
              <param-name>jersey.config.server.provider.packages</param-name>
              <param-value>com.programmertoday.restjersey.api</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>
      

TEST the code

Add a tomcat server and run the project !!

Using any REST client OR any web browser like google chrome open the below url to hit the api.

http://localhost:8080/RESTful_Project/rest/api/department

{"depName":"Information Technology","depCode":"IT"}

Summary

In this article we learnt how to create a simple Jersey based REST API with JACKSON, which leverages us to convert the model class to JSON on the fly. There is no need to write a JSON Array explicitly for this. It’s Super simple and easy !.
Hope you liked the article !