REST Web Services Bascis

Basics of REST with Spring

In the previous post, we learned to build REST API using Spring Boot. Let’s discuss some of the Basics of REST with Spring. We will be covering following topics.

  • Shopping Cart Project: We will use Shopizer API for this.
  • Application Startup, Build and Deployment.
  • Project Configurations.

 

 

1. Shopping Cart Project

Let’s build a real REST API in our course for understanding fundamentals of REST API. We will be building a shopping cart REST API with below features.

  • Ability to get all products based on the store/ site.
  • Get Product details by product ID.
  • Add product to Shopping Cart.
  • Register New User
  • Update User by user id. 
  • Customer Shopping Cart.

 

We will be using Shopizer to build above REST API. Shopizer is a complete e-commerce platform with ready to use features for build e-commerce web applications. Our goal is to build Spring based REST API on the Shopizer platform.

 

 

2. Application Startup, Build and Deployment

Our REST API is based on Spring and Spring Boot. Let’s discuss the process of deploying Spring boot REST application.Spring Boot comes with many built-in features which include flexibility in deploying Spring Boot Applications.

 

2.1 Creating an Executable jar

Spring Boot provides a feature for creating self-contained executable jars which can run standalone in production.An executable jar contains all compiled files along with required dependencies to run our code.

For creating jar, add spring-boot-maven-plugin to the pom.xml file

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Run mvn package command to create jar file under the target directory.Type java -jar target/myproject-0.0.1-SNAPSHOT.jar command to run Spring Boot application.

 

2.2 Embedded Web Server Deployment Tomcat

We added spring-boot-starter-web in our application.When we run our application, Spring Boot will detect Spring MVC in the classpath and startup embedded Apache Tomcat server.We can configure and customize embedded tomcat using application.properties file

  • Enable HTTPS for REST API.
  • Configure server port
  • Add HTTPS certificate.

Read  Spring Boot Web Application Configuration for more detail.

 

2.3 Embedded Jetty Server

If you like to use Jetty as the embedded server, you need to add spring-boot-starter-jetty to your pom.xml.Spring Boot will automatically delegate work to Jetty. Here is the updated POM for Embedded Jetty server.

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

There are few things which are interesting in above configuration

  • We excluded spring-boot-starter-tomcat to ensure only one embedded server is available for our application.
  • Jetty server was added using spring-boot-starter-jetty

 

 

2.4 Standalone Application Server

What if you like to deploy your REST application on an existing Tomcat instance or to Java EE application servers like Apache Tomcat EE, WildFly or Websphere? You need to make only a few changes to make sure your application is ready for the deployment of these servers.

  • Change application packaging from jar to war in your pom.xml.
  • Remove spring-boot-maven-plugin from the pom.xml.
  • Need to add web entry point (We will be using Servlet 3 Java configuration)

 

To enable our application, we will add ServletInitializer class. On a high level, our class will look like something 

package com.example.demo;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

public class CustomWebApplicationInitializer extends SpringBootServletInitializer {

    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(applicationClass);
    }

    private static Class applicationClass = DemoApplication.class;

}

 

 

3. Project Setup

Please read our previous article Building Restful Web Services to get an understanding of the project structure in Spring Boot.In addition to this structure, we will start adding extra components and libraries to this structure. If you are starting with this post, I highly recommend reading our last post to start with.

 

Summary

In this post of Building REST services with Spring, we covered Basics of REST with Spring.We discussed the REST application which we will be creating during this course. We also covered some of the basics of deploying our Spring Boot REST application. 

Spring Singleton vs Singleton Pattern

Spring Singleton vs Singleton Pattern

Spring singletons are not Java Singleton. In this post, let’s go over the difference between Spring Singleton vs Singleton Pattern.

 

Introduction

Singleton scope is the default scope in Spring. Spring container create exactly one instance of the object defined by that bean definition.

Many times, we start comparing this design with the Singleton pattern as defined in the Gang of Four (Gof) book.

 

 

1. Singleton Scope vs Singleton Pattern

Singleton scope in Spring is not same as singleton pattern. Some of the main differences between these 2 are

  • Singleton pattern ensures one instance of a particular class of per class loader.
  • Spring Singleton is  “per container per bean”.

If you pay close attention, these are entirely different design in terms of how they define singleton.

 

1.1 Singleton Scope Example 

Singleton instance in Spring will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

Let’s work on an example to understand it more clearly.

public class CustomerAccount {

    private String name;

    public CustomerAccount() {
    }

    public CustomerAccount(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return "CustomerAccount{" +
                "name='" + name + '\'' +
                '}';
    }
}

 

Spring Boot main method

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {

		SpringApplication.run(DemoApplication.class, args);
	}

	@Bean(name = "bean1")
	public CustomerAccount customerAccount(){
		return new CustomerAccount("Test User 1");
	}

	@Bean(name = "bean2")
	public CustomerAccount customerAccount1(){
		return new CustomerAccount("Test User 2");
	}
}

 

Let’s understand this code.

  • We created 2 instances of the same class with different bean id.

How many instances created by Spring IoC container for above example? 

  1. 2 separate instances in the container bind to their Id’s?
  2. 1 instance bind to 2 bean ids?

 

1.2 Test Case 

To get an answer to the above questions, let’s create a unit test case for our example.

@RunWith(SpringRunner.class)
@SpringBootTest
public class SingletonScopeTest {

    private static Logger log = LoggerFactory.getLogger(SingletonScopeTest.class);

    @Resource(name = "bean1")
    CustomerAccount account1;

    @Resource(name = "bean1")
    CustomerAccount duplicateAccount;

    @Resource(name = "bean2")
    CustomerAccount account2;

    @Test
    public  void testSingletonScope(){
        log.info(account1.getName());
        log.info(account2.getName());

        log.info("account are equal:: {}", account1 == account2);
        log.info("Duplicate Account :: {}", account1 == duplicateAccount);
    }
}

 

Output

2018-01-15 21:53:29.171  INFO 8421 --- [           main] com.example.demo.SingletonScopeTest      : Test User 1
2018-01-15 21:53:29.171  INFO 8421 --- [           main] com.example.demo.SingletonScopeTest      : Test User 2
2018-01-15 21:53:29.171  INFO 8421 --- [           main] com.example.demo.SingletonScopeTest      : account are equal:: false
2018-01-15 21:53:29.172  INFO 8421 --- [           main] com.example.demo.SingletonScopeTest      : Duplicate Account :: true

On checking the output, We found

  • we can understand that Spring returns two different instances.
  • More than one object of the same class for the singleton scope.

 

For a given Id, Spring container maintain only one shared an instance of singleton bean. In our example

  • Spring Ioc container created 2 instances of the same class based on bean definition and binds them with ids.
  • Spring bean definition work as a key-value pair, the key is mapped to bean id and value mapped to the bean instance.
  • Each key reference returns the same bean instance (refer to “bean1” always return bean instance associated with id “bean1”).

 

Summary

Spring Singleton is very different to Singleton pattern. Spring guarantees to create only one bean instance for given bean id definition per container.Singleton pattern ensures that one and only one instance is created per ClassLoader. 

Spring Bean Scopes

Spring Bean Scopes

In this post, we will cover different types of bean scopes in Spring Framework. We will cover different Spring Bean Scopes with their use case.

 

Introduction

Bean definition in Spring is to create a recipe for creating the actual instance of the class defined in the Bean.Spring Framework provides different scopes to create an object based on the bean definition.

Spring out of the box supports following 7 Bean Scopes 

  • singleton
  • prototype
  • request
  • session
  • application
  • websocket
  • globalSession

 

 

1. The singleton scope

Spring Bean defined with singleton scope will have only one instance. To put it in a simple term, Spring Ioc container will create exactly one instance for that object. Spring container will always return the same instance. Spring Framework use store all singleton bean in the cache and all request and references for that bean will be returned from the cache. The singleton scope is the default scope in Spring.

Let’s create an Order entity to understand it more clearly

public class OrderService {
    
    @Bean
    @Scope("singleton")
    public OrderService getOrder(){
        return new OrderService();
    }

}

 

If you want you can use ConfigurableBeanFactory to define scope using constant value than String.

@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)

 

To define bean as singleton in 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.xsd">
    
<bean id="orderService" class="com.javadevjournal.demo.service.OrderService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="orderService" class="com.javadevjournal.demo.service.OrderService" scope="singleton"/>
</beans>

 

 

2. The prototype scope

Singleton bean is suitable for stateless beans. A new instance of prototype bean will be created by Spring container every time a request is made to this bean. For example, if we are injecting this bean into another bean, a new instance of this prototype bean will be created every time a request made to the parent bean.

Prototype scope is best suitable for stateful beans.

public class OrderService {
       
    @Bean
    @Scope("prototype")
    public OrderService getOrder(){
        return new OrderService();
    }

}

There are few interesting things about prototype scope.

  • Spring container does not manage the complete lifecycle of these beans.
  • IoC container creates prototype bean and hands over this to the client, it is the responsibility of the client to manage this bean.
  • Spring container take care of cleaning up resources in case bean is no longer in use, for prototype scope, configured destruction lifecycle callbacks are not called.
  • The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.
  • Always use custom bean post processor to perform cleanup work (recommended).

 

Rest of the bean scopes,

  • request scope
  • session scope,
  • application scope,
  • websocket scope

are only available in the web-aware application. They need some minor configurations before we can define and use these scopes in our application. 

  • For Spring Web MVC application all these scopes are available and exposed by DispactherServlet and no additional setup is required.

 

If you are not using Spring’s DispactherServlet, you need to configure org.springframework.web.context.request.RequestContextListener in your application. you can use web.xml or Spring WebApplicationInitializer for Servlet 3.0+.

 

 

3. The request scope

Spring container will create a new instance of request scope bean for each and every HTTP request.

public class AddToCart {

    @Bean
    @RequestScope
    public AddToCart getCart(){
        return  new AddToCart();
    }
}

XML configuration for request scope bean

<?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.xsd">
    
<bean id="addToCart" class="com.javadevjournal.demo.AddToCart" scope="request"/>
</beans>

AddToCart instance is scoped at the request level.

  • We can change AddTOcart instance to any level as other instance created for this scope will not have any information on the changes done to this AddTocart instance.
  • Spring container will discard this bean once the request completes processing.

 

 

4. The session scope

Spring container will create a new instance of the session scope bean for the lifecycle of a single HTTP session.This works similar to request scope beans in terms of the visibility of the bean internal status to other bean created in different HTTP session.

public class AddToCart {

    @Bean
    @SessionScope
    public AddToCart getCart(){
        return  new AddToCart();
    }
}

 

XML configuration for session scoped bean

<?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.xsd">
    
<bean id="addToCart" class="com.javadevjournal.demo.AddToCart" scope="session"/>
</beans>

 

 

5. The application scope

Spring container creates only one bean definition for the entire web application. 

public class SystemConfiguration {

    @Bean
    @ApplicationScope
    public SystemConfiguration getConfig(){
        return  new SystemConfiguration();
    }
}

 

XML configuration for application scoped bean

<?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.xsd">
    
<bean id="addToCart" class="com.javadevjournal.demo.SystemConfiguration" scope="application"/>
</beans>

 

6. The WebSocket scope

The WebSocket scope is new scope in the Spring Framework.

@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class WebSocketBean {

    //Web Socket Bean
}

Spring IoC container creates a new bean instance per WebSocket Session

 

7. The GlobalSession scope

The globalSession scope is more connected to the Portlet environment.Bean created under globalSession scope will be available for all portlet. This scope work similar to session scope beans under servlet environment.

public class GlobalSessionBean {

    @Bean
    @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
    public  GlobalSessionBean getGlobalSession(){
        return new GlobalSessionBean();
    }
}

 

Note :

As of Spring 3.0, a thread scope is available which is not register by default and need to be registered like any other custom scope bean. Read for more detail.

Summary

In this post, we discussed different Spring Bean Scopes and what their intended usages are.It is always good to have a clear understanding of the bean scopes. 

Java 8 Date Time API

Introduction to the Java 8 Date Time API

 

Java 8 introduced a new API for Date and Time. In this post, we will cover some of the features of the Java 8 Date Time API

 

Introduction

Java 1.0 introduced support for date and time using java.util.Date class.This API contains a lot of issues including not representing the date as a human-readable date but point in time with milliseconds.We will cover some of the issues or drawbacks of the existing Date API which made way for the Java 8 Date Time API

 

1.  Issues with the Existing Date Time API

  • API Design – Initial Date class introduced in Java 1.0 was not a true representation of the date but a point in time with milliseconds as precision. Calander API introduced as a replacement was poorly designed and lead to confusion in day to day use.
  • Thread Safety – The Date and Calander classes are not thread-safe.None of the instance methods are synchronized, and none of the instance fields are volatile, even get method can cause an instance of these classes as Mutable. A developer needs to ensure thread safety in case they are using these classes.
  • Usability – Most of the methods provided by Java before Java 8 Date Time API were lacking readability and needs a more clear understanding of the underlying working of the code before using it.

 

Due to all these designs flaws and inconsistencies, most of the enterprise applications were forced to use third party solution like Joda-Time etc. To resolve all these issues, Java 8 introduced a brand new Date and Time API which is integrate many of the Joda-Time API features.

 

 

2.  LocalDate, LocalTime and LocalDateTime

LocalDate, LocalTime, and LocaleDateTime are the most commonly used classes in the new Date API. These classes provide information independent of time zone i.e we do not need to worry about the time zone.

 

2.1 Working with LocalDate

LocalDate represents date without time zone in ISO format. This is one of the most commonly used classes in the new Date API.An instance of this class is immutable and represents date without information of the time and timezone.

LocalDate provides multiple utility methods to create an instance of this class. We can use of static factory method of the LocalDate class to create an instance of this class.

LocalDate date = LocalDate.of(2018, 01,8); //2018-01-08

Above code will represent the LocalDate for 8 January 2018. LocalDate instance provides a number of different methods which can be used for the most common values required while working to Date. We will cover some of the methods in this section.

 

LocalDate date = LocalDate.of(2018, 01,8);

int year = date.getYear(); //2018.
boolean isLeap = date.isLeapYear(); //f alse, 2018 is not Leap Year
int day = date.getDayOfMonth(); // 8
DayOfWeek dayOfWeek =date.getDayOfWeek(); //MONDAY
Month month =date.getMonth(); //JANUARY
int monthLength = date.lengthOfMonth(); //31
int daysOfYear = date.getDayOfYear(); // 8

 

We can use LocalDate.now() factory method to obtain current date based on the system clock.

LocalDate systemDate = LocalDate.now(); //2018-01-08

LocalDate provides other utility methods to get a different kind of information. We will cover different operations that can be performed on the LocalDate object in other section of this post.

 

 

2.2 Working with LocalTime

LocalTime represents a time of the day (e.g 20:22: 12) without time zone and date.Like LocalDate, we can get an instance of LocalTime by using the static factory method.

LocalTime time = LocalTime.of(20, 45);  //20:45
LocalTime time = LocalTime.of(20, 45, 12);  //20:45 : 12

 

LocalTime class provides numbers of utility method to get information from the LocalTime instance.

LocalTime time = LocalTime.of(20, 45, 34);  //20:45:34

int hour = time.getHour(); //20
int minutes = time.getMinute(); //45
int seconds = time.getSecond(); //34

 

To get time zone independent current LocalTime based on the system clock, we can use LocalTime.now() factory method.

LocalTime systemTime = LocalTime.now(); //20:49:35.509403

 

We can also create an instance of LocalTime by parsing String using LocalTime.parse() method

LocalTime systemTime = LocalTime.parse("15:45:45"); //15:45:45

 

 

2.3 Working with LocalDateTime

LocalDateTime is the combination of LocalDate and LocalTime. LocalDateTime represents date and time without time zone. We can create an instance of the LocalDateTime class by using now method or we can combine date and time instance to create the LocalDateTime object.

LocalDateTime localDateTime = LocalDateTime.of(2018, Month.JANUARY, 8, 21, 26, 12); //2018-01-08T21:26:12

LocalDate date= LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime combieDataIssue = LocalDateTime.of(date,time); //2018-01-08T21:30:03.663603

LocalDateTime ldt = date.atTime(time);  //2018-01-08T21:41:50.068417
LocalDateTime ldt1 = time.atDate(date);  //2018-01-08T21:41:50.068417

 

 

3.  Period and Duration

Use Duration class to represent time in seconds and nanoseconds and Period for time in years, months and days.

 

3.1 Duration

Duration is the time-based amount of time (e.g 12.4 seconds etc), here are some of the example for Duration

Duration twoMinutes = Duration.ofMinutes(3);
Duration duration = Duration.of(3, ChronoUnit.MINUTES);

LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime localDateTime1 =LocalDateTime.of(2018, Month.JUNE, 5, 10, 15, 45);

Duration duration1 = Duration.between(localDateTime1, localDateTime);

 

 

3.2 Period

A date-based amount of time in the ISO calendar system.The period class can be used to modify a value for a given date or to find the difference between dates. Let’s take an example to understand how this can be used.

LocalDate initialDate= LocalDate.of(2017, 10, 11);

 

Use period class to get useful information from the 2 date instances.

Period days = Period.ofDays(4);
Period weeks = Period.ofWeeks(3);


LocalDate initialDate= LocalDate.of(2017, 10, 11);
LocalDate finalDate =  LocalDate.of(2017, 11, 15);

int dayDuration = Period.between(initialDate, finalDate).getDays(); //4
int monthDuration = Period.between(finalDate,initialDate).getMonths();  // -1

 

 

4.  Modify Dates Instance

One of the main features of the Java 8 Date Time API is thread safety and most of the classes we discussed are immutable.In certain cases, we might need we need a new instance of the give LocaleDate instance to work with.

To create a new object for the given LocalDate, we can use one of it’s withAttribute or more generic with a method.

LocalDate currentDate = LocalDate.now(); //current system date
LocalDate withYearDate= currentDate.withYear(2017); //Returns a copy of this date with the year altered //2017-01-09

LocalDate daysOfMonth = withYearDate.withDayOfMonth(12);  // Returns a copy of this date with the day-of-month altered // 2017-01-12

 

These methods return a new object without keeping original LocalDate instance unchanged.

 

5.  Manipulate Dates

New Java 8 Date Time API provides convenient ways to manipulate LocalDate instance. We can perform add, subtract on given Date instance.

 

//Date Manipulation

LocalDate date = LocalDate.of(2017, 8, 23);
LocalDate date1 = date.plus(1, ChronoUnit.DAYS);  // 2017-08-24
LocalDate date2 = date1.plusWeeks(1);  // 2017-08-31 , one week added to date
LocalDate addYear = date2.plusYears(2);  // 2019-08-31 , added 2 years
LocalDate minusYear = date2.minusYears(4);  // 2013-08-31

LocalDate fromYear = minusYear.from(ZonedDateTime.now());

 

Please note that like with and withAttribute methods defined in the earlier section, These methods return a new Object with modified attributes.

 

 

6.  Parsing Dates

Before Java 8 parsing and formatting of Date object were not very easy. Java 8 new java.time.format package provides a lot of helpful methods to format or parse date easily.

DateTimeFormatter is one of the most important class under this package. We can use parse() method of the LocalDate instance to format given date instance.

LocalDate date = LocalDate.of(2011, 12, 17);
String formattedDate = date.format(DateTimeFormatter.BASIC_ISO_DATE); // 20111217

 

Use DateTimeFormatter for converting String to the LocalDate instance.

LocalDate stringFormattedDate = LocalDate.parse("20161217", DateTimeFormatter.BASIC_ISO_DATE); // 2016-12-17
LocalDate date1 = LocalDate.parse("2016-08-17", DateTimeFormatter.ISO_LOCAL_DATE); // 2016-08-17

 

DateTimeFormatter provides a number of formatter to work with, however,

    • what are the option if we want to format a date for which we do not have formatter provided by DateTimeFormatter class.

The DateTimeFormatter class provides a static factory method for creating custom formatter.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate currentDate = LocalDate.now(); // output : 2018-01-09

String formattedDate1 = currentDate.format(formatter); // output : 09/01/2018 in
LocalDate newDate = LocalDate.parse(formattedDate,formatter);

 

So we did few things in above example of created new LocalDate instance based on new formatter.

  • We created DateTimeFormatter for dd/MM/yyyy format.
  • We created String representation of the LocalDate instance.
  • Used parse method provided by LocalDate class to create a new instance with required format.

 

If you are looking for Local based formatter, use the overloaded method of DateTimeFormatter by passing Local as an additional parameter.

DateTimeFormatter japaneseFormatter = DateTimeFormatter.ofPattern("M'月' yyyy'年'", Locale.JAPANESE);
String newFormatter = currentDate.format(japaneseFormatter); // output : 1月 2018年
LocalDate localDate = LocalDate.parse(formattedDate1,formatter);

 

This is numbers of benefits of using this new formatter.

  • This is thread safe as compare to old DateFormat class.
  • We can use the single instance of this formatter across multiple threads.

 

The parse() method can throw DateTimeParseException in case it is not able to parse String to a valid LocalDate or LocalTime instance.

 

6.1 Using DateTimeFormatterBuilder

New Java Date and Time API provide DateTimeFormatterBuilder class to create complex formatter.

DateTimeFormatter builder = new DateTimeFormatterBuilder()
        .appendLiteral("Day of Month is :")
        .appendValue(ChronoField.DAY_OF_MONTH)
        .appendLiteral(", Month is :")
        .appendValue(ChronoField.MONTH_OF_YEAR)
        .appendLiteral(", Year is : ")
        .appendValue(ChronoField.YEAR)
        .appendLiteral(", Time is :")
        .appendValue(ChronoField.HOUR_OF_DAY)
        .appendLiteral(":")
        .appendText(ChronoField.MINUTE_OF_HOUR, TextStyle.FULL_STANDALONE)
        .parseCaseSensitive()
        .toFormatter();

LocalDateTime localDateTime = LocalDateTime.now();
String date = localDateTime.format(builder);

 

Output

Current Day is :9, Month is :1, Year is : 2018, Time is :21:16

 

 

7. Java Date Time API Features

We covered some of the basic features of Java 8 Date and Time API. There are numbers of features improvement this new API brings in, here are some of the most important features of new API.

  • Most of the classes provided by new API are immutable which is more in line with functional programming introduced with Java 8.
  • Better readability, think about Calander.getInstance() method as compare to LocalDate.now() or LocalTime().
  • The new API uses immutable objects, which makes it thread safe.

 

 

Summary

In this article, we covered Java 8 Date Time API. We covered different features and improvement introduced by Java Date and Time API. This API is a complete replacement of the old Java API and integrate many of the features of Joda-Time API.

Building Restful Web Services

Building Restful Web Services with Spring

This post will guide us through the process of Building Restful Web Services with Spring. If you are starting your project, our recommendation is to use  Spring Boot to build your Restful Web Services. In case you don’t have the option to use Spring Boot, just navigate to the second part of this post for using traditional way to of  Building Restful Web Services with Spring.

 

1. Build Restful Web Services using Spring Boot

There are multiple ways of creating REST services using Spring Boot. Here are the different options

  1. Spring Boot Initializr.
  2. Using Maven.
  3. IDE of your choice.

What you will need

  • IDE
  • JDK 1.8 or later
  • Maven (You can also opt for Gradle)

 

1.1 Spring Boot Initializr

This is the simplest way to build Spring Boot REST API.Open Spring Initializr in your browser.You will be presented with a wizard to start your configurations.

Building an Application with Spring Boot

 

Fill out the relevant details in the wizard, add “Web” (We will add other required dependencies while we are working on our REST service series.) in the dependencies section and hit generate button.Spring Initializr will generate a base project, you will be given a zip to download. You can import the unzipped project as a simple maven/ gradle based project in your IDE. Refer to Creating a Web Application with Spring Boot for more detail.

 

1.2 Using Maven

I will not be covering how to create a simple project using Maven. Once you have simple Java project using Maven, we need to update pom.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.javadevjournal</groupId>
    <artifactId>rest-service-series</artifactId>
    <version>0.1</version>
    <description>Build RESTful Webservices using Spring</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

     <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <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>

     <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>   

   </project>

 

Most of the main work is being taken care by Spring Boot Maven Plugin

 

1.3 Using IDE

Most of the modern IDE provide direct support for building REST services using Spring Boot. I personally use IntelliJ IDEA but you can use Eclipse or even Spring Tool Suite (STS).

 

1.4 Resource Representation

We discussed basic principles of RESTfull API in our first articles What is REST API. A resource is one of the fundamental concepts of REST services. Basic project setup is complete, we can now start working on creating our REST web service.

We will work on a simple service interaction.

  • Service will handle GET request for /product with a productCode parameter in the query string.
  • Service should return 200 OK response with JSON (we will cover other formats in this series) data in the body which represents our product information.

This is how our JSON response will look like

 

{  
   "code":"K123456",
   "name":"Super Product",
   "description":"We build this product during our REST service course",
   "price":100.00
}

We will now create resource representation class for the product.This will be plain old Java object

package com.javadevjournal.rest.model;

public class Product {

    private String code;
    private String name;
    private String description;
    private double price;

    public Product() {
    }

    public Product(String code, String name, String description, double price) {
        this.code = code;
        this.name = name;
        this.description = description;
        this.price = price;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

As part of the next step, we will create our first resource controller which will handle REST request and will send the response in JSON format.

REST Controller
package com.javadevjournal.rest.controller;

import com.javadevjournal.rest.controller.service.ProductService;
import com.javadevjournal.rest.model.Product;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
class ProductController {

    @Autowired
    ProductService productService;

    @RequestMapping("/product")
    public @ResponseBody
    Product getProduct(@RequestParam(value = "code") String productCode) {

        return productService.getProductByCode(productCode);
    }
}
Service Class
package com.javadevjournal.rest.controller.service;

import com.javadevjournal.rest.model.Product;

import org.springframework.stereotype.Service;

@Service("productService")
public class ProductService {

    public Product getProductByCode(final String productCode){

        Product product = new Product();
        product.setCode(productCode);
        product.setName("Super Product");
        product.setDescription("We build this product during our REST service course");
        product.setPrice(100.00);

        return product;
    }
}

This is the first example of our REST web service API. Our controller is simple but there are multiple things going on under the hood

  • @RequestMapping annotation ensures that request to /product is mapped to the getProduct method.
  • We need to pass product code to the method, @RequestParam is responsible to bind query string parameter to code.
  • getProduct() method call getProductByCode() which simply creates Product and fills sample data.
  • The code is using @RestControler annotation (not @Controller annotation) which was introduced in Spring 4.
  • One of the main features of @RestController annotation is its ability to return domain object for every method call and not view.
  • @RestController is a combination of @Controller and @ResponseBody annotation together.
  • The @ResponseBody annotation tells Spring MVC to write return object in the response and not use the view.
  • Product data needs to be converted to JSON, this is automatically taken care by Spring’s HTTP message converter support.
  • We used Spring Boot to bootstrap our REST web service, it automatically added Jackson 2 to the classpath. Spring’s MappingJackson2HttpMessageConvertor will automatically handle conversion of Product to JSON.

 

There are few key points which differentiate our REST controller from a conventional controller which is responsible for returning a view.

 

  • We are not returning any view from our controller but returning actual domain object (Product in our case).
  • This Product data will be written directly in the response as JSON, XML or YAML format (JSON in our example).

 

 

1.5 Run Application

We will run our application by using SpringApplication helper class from Spring Boot.

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

@SpringBootApplication
public class RestServiceSeriesApplication {

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

Once our service is up and running, visit  http://localhost:8080/product?code=KI03811 and you should be able to see

{
code: "KI03811",
name: "Super Product",
description: "We build this product during our REST service course",
price: 100
}

We have created and deployed a REST web service with Spring Boot.

 

 

2. Build Restful Web Services using Spring MVC (Not Spring Boot)

In this section, we will cover how to create REST web services using Spring. There is still a possibility that you are not using Spring Boot for your project. We will discuss the process to Bootstrap a Web Application with Spring.

 

2.1 Create Simple Web Application using Maven

We will be using Maven to create a simple web module, once the module is created by Maven, we will start expanding our application for supporting our REST web service

You can use IntelliJ IDEA, Eclipse or any other IDE to create web module using Maven. (We will not be covering project creation in this post).

 

2.2 Maven pom.xml

Once our web module is created, we need to add required Spring MVC dependencies for out REST module. 

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javadevjournal</groupId>
    <artifactId>restserviceseries</artifactId>
    <packaging>war</packaging>
    <version>01.-SNAPSHOT</version>
    <name>rest-service-series Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.version>4.3.13.RELEASE</spring.version>
        <jackson-version>2.9.0</jackson-version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson-version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
        <finalName>rest-service-series</finalName>
    </build>
</project>

 

2.3  Java based Web Configurations

Let’s create our Spring MVC configuration which will be responsible for providing startup configurations for our web application. I will not be covering XML based configuration but you can find number of example on the net (if you prefer)

package com.javadevjournal.rest.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.javadevjournal.rest"})
public class AppConfig {

    // required configurations
}

Let’s start looking at our example in details to understand different aspects of it.

The @Configuration annotation is the central artifact of Spring’s Java-configurations.@Configuration is a meta-annotated as a @Component which make is eligible for component scanning, it also gives the flexibility to use @Autowired annotations. A class annotated with @Configuration annotation indicates that this can be used by Spring IoC container for bean definitions.

 

@EnableWebMvc annotation to an @Configuration class will imports Spring MVC configurations from WebMvcConfigurationSupport. In simple terms, it will register a number of Spring MVC infrastructure beans which are needed for MVC application (e.g  Data / Payload converter etc). If you are familiar with XML based configurations, it is equivalent to <mvc:annotation-driven/>.

 

@ComponentScan annotation with @Configuration classes class provides support parallel with Spring XML’s <context:component-scan> element. This will enable Spring to scan all classes through the given package and will register all beans and controller for our application.

 

 

2.4  The DispatcherServlet

With Servlet 3.0, we can define our container configurations without the web.xml file. Read Spring WebApplicationInitializer to get understand the Java-based configuration.

package com.javadevjournal.rest.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class CustomWebAppInitializer implements WebApplicationInitializer {
    /**
     * Configure the given {@link ServletContext} with any servlets, filters, listeners
     * context-params and attributes necessary for initializing this web application. See examples
     * {@linkplain WebApplicationInitializer above}.
     *
     * @param servletContext the {@code ServletContext} to initialize
     * @throws ServletException if any call against the given {@code ServletContext} throws a {@code
     *                          ServletException}
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(AppConfig.class);

        // Manage the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(rootContext));

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher =
                servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

 

2.5  REST Controller

Our infrastructure is ready, let’s create our REST Controller, which will return Product in the response. For more details about REST controller structure and representation, please refer to section1.

@RestController
class ProductController {

    @RequestMapping("/product")
    public @ResponseBody
    Product getProduct(@RequestParam(value = "code") String productCode) {

        return getProductByCode(productCode);
    }

    private Product getProductByCode(final String productCode){

        Product product = new Product();
        product.setCode(productCode);
        product.setName("Super Product");
        product.setDescription("We build this product during our REST service course");
        product.setPrice(100.00);

        return product;
    }
}

 

2.6  Run Application 

Build and deploy your application.Once our service is up and running, visit  http://localhost:8080/product?code=KI03811 and you should be able to see

{
code: "KI03811",
name: "Super Product",
description: "We build this product during our REST service course",
price: 100
}

We have created and deployed a REST web service with Spring.

 

 

Summary

In this article on REST with Spring, we covered how to create REST web service using Spring Boot and Spring MVC.

What is REST API

What is REST API

In this post, we will try to cover some of the basic questions around REST API  and one of the main questions is “What is REST API“?

 

Introduction

REST is a short form of REpresentational State Transfer. Introduced by Roy Fielding, REST is an architecture style for distributed hypermedia systems. REST is not a standard but think of it as a set of constraints or principles which must be satisfied if we want to refer to an interface as RESTful.

 

1. Principles of REST

REST is a simple term can be called as a set of contains or principles which every interface must follow to be called as RESTful.

 

1.1 Stateless

Every request between client to server should have all the information needed to understand the given request and server is correct.A server should not store any client context between requests.This is one of the main principles of the REST design.

 

1.2 Client Server 

This constraint is added to have a separation of concern. By clearly defining client and server, we are separating user interface concerns (client) from the data/business process (Server). This design adds a lot of portability.

 

1.3 Cachable

Response data for a request should have a clear indication for cacheable or non-cachable data. If a data is marked as cacheable, the client has the flexibility to reuse this data for later use.

 

1.4 Resources

A resource is one of the fundamental concepts in REST API.A resource is a representation of anything that can be named e.g. image, a service, shopping cart, order, customer and so on.We can also think of the resource as an object having a type (e.g. ShoppinCart, Customer), data (e.g. ShoppingCart contain products) and maybe relation with another resource (e.g. ShoppingCart belong to a Customer).

RESTful API uses a resource identifier to identify a resource for a given interaction between client and server.Resource Representation indicated the state of the resource at a given time. Representation can have the following information

  1. Data for the resource.
  2. Metadata describing data in the given resource.
  3. hypermedia

 

With RESTful API, we have a resource if we have the URL, so /products/{productID} represents product resource for single product while /products is likely the address for collection of resources of products

 

1.5 Representations

Representation refers to the representation of the data objects and attributes (e.g in JSON or XML format). Let’s take a quick look at the customer resource representation

{
    "firstName": "David",
    "age": 35,
    "phone": "9111111111"
}

 

Above is a representation of the client resource.This is an example of the JSON format but this can vary based on your choice. Below is the list of known representation for the resource.

  • JSON
  • XML
  • YAML

 

2. REST and HTTP

This is one of the basic misunderstandings if you are starting with REST. REST and HTTP are not same. One of the main benefits of REST is to streamline web-based applications but this does not mean that any HTTP interface is a REST API.

To summarize

  • In a RESTful architecture, data and business functionalities are considered as resources.
  • These resources should be accessed using Uniform Resource Identifiers (URIs).
  •  Client and server will always exchange representation of resources (JSON or XML etc).

If you want more detailed answers to your question of “What is REST API ?” Please refer to following additional resources.

  1. How I Explained REST to My Wife
  2. steps toward the glory of REST
  3. RESTful Web Services
  4. Representational State Transfer (REST)

 

2. REST With Spring

Spring started supporting RESTful services with 3.0, here are some of the ways provided by Spring 3.x 

  • Use Spring MVC @RestController with ModelAndView
  • Use Message Converter

 

We will not cover ModelAndView approach as it is old an not suitable for the modern RESTful services. Spring 3.0 has the options to use annotation with HttpMessageConvertor which carry following advantages

  • Easy implementation with lightweight.
  • Minimal configurations.
  • Spring MVC provides multiple default settings for the RESTful APIs.

 

2.1 REST With Spring MVC 4.0

Spring 4.0 enhanced REST support by introducing @RestController annotation.With this annotation, you are no longer required to annotation all of our @RequestMapping methods with @ResponseBody.

@RestController Annotation combines @ResponseBody and @Controller annotation.If you are starting building your REST API, my recommendation is to use this annotation as it provides more ready to use REST API features, additionally, this provides a more meaningful name along with an option that it may carry additional semantics in future releases of the framework.

 

Summary

In this post, we discussed What is REST API and what are the principle if we want to design a REST API. We briefly discussed REST support in Spring Framework.In the next article, we will discuss the process of Building Restful Web Services with Spring 

This is an ongoing series on building REST API using Spring. If you are starting with REST, I highly recommend getting a clear understanding of the REST architecture before you dive into Spring with REST API guide.

Spring Boot Auto Configuration

Spring Boot Auto Configuration

One of the powerful features of Spring Boot is its ability to automatically configure our application based the jar dependencies we are adding to our classpath. In this post, we will be covering Spring Boot Auto Configuration features with an understanding of how this can help in the development lifecycle.

 

Introduction

We can start by raising very simple questions, Why do we need Spring Boot Auto Configuration? What are the benefits of using Spring Boot for our application? To get better answers to these questions let’s take a look at the configurations needed for create a simple Spring MVC application without Spring Boot. (These configurations are from Shopizer which we are migrating to Spring Boot)

<beans:beans>
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
 	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	
	<beans:bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <beans:property name="defaultLocale" value="en"></beans:property>
    </beans:bean>
<!-- other configuration -->
</beans:beans>

 

We also need to configure dispatcher servlet in Web.xml file as part of the configuration. For Database applications, we need additional configurations for Hibernate / JPA along with datasource and other configurations.

With enterprise Spring applications, these configurations can become quite complex and we might end up configuring lots of things to start our application.

 

 

1. What is Auto Configuration

What if the system can provide some default setup based on the jars in the classpath along with options to override it based on our requirements

  • Default servlet container for ourSpring MVC application?
  • What about is system will configure default dispatcher servlet for us

 

Spring Boot Auto Configuration comes with these features. Auto-Configuration will attempt to automatically try to set up our application with default behavior based on the jars in the classpath. For example, if Spring Boot finds HSQLDB in out classpath, it will automatically configure an in-memory database for us.

think of the auto-Configuration as an intelligent system which can provide ready to use the application to us based on the configured jars in our classpath.

 

 

2. Auto Configuration in Action

To get an understanding of how Spring Boot Auto Configuration works internally, we can create Spring MVC application using Spring Boot. Follow    Creating a Web Application with Spring Boot to create an application using Spring Boot.

Run your MVC application and look at the console. You might find similar output in the console.


2017-12-21 20:53:34.429 INFO 51206 --- [ main] org.apache.catalina.core.StandardEngine : 
Starting Servlet Engine: Apache Tomcat/8.5.23 
2017-12-21 20:53:34.523 INFO 51206 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 
2017-12-21 20:53:34.524 INFO 51206 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1496 ms 
2017-12-21 20:53:34.749 INFO 51206 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 
2017-12-21 20:53:34.754 INFO 51206 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 
2017-12-21 20:53:34.755 INFO 51206 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 
2017-12-21 20:53:34.756 INFO 51206 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 
2017-12-21 20:53:34.756 INFO 51206 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]

 

In our sample application, we never defined any dispatcher servlet or configured tomcat for the deployment, however, we can still find  Mapping servlet: 'dispatcherServlet' to [/] in the console, this is happening because we added spring-boot-starter-web in our application using POM.xml

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

 

This single entry demonstrates power and feature of auto-configuration. On adding this starter in our application, Spring Boot auto configuration understands that we are building an MVC application and it added all required dependencies in our classpath for a Spring MVC web application.

This went one step ahead and automatically configured DispactherServlet, CharacterEncodingFilter, RequestContextFilter and even error page for us (We never did any configuration for these). Spring Boot will add similar configurations based on the Spring Boot Starters added in the POM file.

 

 

2. Auto Configuration Details

Let’s check how auto configurations work internally, check what is added to the classpath using IDE (Eclipse or IntelliJ etc).

Here is the one from our sample application.

Spring Boot Auto Configuration
Spring Boot Auto Configuration

As seen in this above screenshot, Spring Boot automatically added dependencies for us to ensure we have ready to use application.

 

2.1 Spring.Factories

To enable auto-configuration for our application, we can either use @AutoConfiguration or @SpringBootApplication annotation in our application. Check spring.factories property file under /META-INF directory under spring-boot-autoconfigure.jar.

 

Spring-boot-autoconfigure
Spring-boot-autoconfigure

This file contains a list of the auto-configuration classes which will be automatically enabled by Spring Boot. Here is a sample output from spring.factories file.

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\

Here is how auto-configuration class look like

@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass(DispatcherServlet.class)
@AutoConfigureAfter(EmbeddedServletContainerAutoConfiguration.class)
public class DispatcherServletAutoConfiguration { 
//configuration code
}

We will be covering these annotations and other details in a separate post.

 

Summary

In this post, we covered Spring Boot Auto Configuration feature. We covered some of the interesting features of Configurationation along with how this works internally.

The interesting features of Spring Boot Auto Configuration are its ability of noninvasive.Define your own configuration to replace default auto-configuration

If you are starting with Spring Boot, read our other articles on Spring Boot

Spring Boot Dev Tools

Introduction to Spring Boot Dev Tools

Spring Boot comes with a lot of features and one of such feature is to help in developer productivity. In this post, we will be covering about Spring Boot Dev Tools.

 

Introduction

One of the main advantages of using Spring Boot is it’s production ready features, in order to provide these features, Spring Boot use certain predefined configurations.

  • If you use Thymeleaf for your application, it’s caching is enabled by default until we switch it off.
  • We need to quickly deploy our code changes with minimal deployment and server restart time.

These features are good but can slow down development when we will be making frequent changes in our code and want to see changes immediately.We have the option to use 3rd party tools like Jrebel to help in this but these tools are not free and need a significant amount to get license (Jrebel is really a great tool and if you can get it, I will highly recommend it) 

Spring Boot 1.3 introduced Spring Boot Dev Tools module which was aimed to help developers in improving the productivity.  We will be covering following features of the Spring Boot Dev Tool

  • What is Spring Boot Dev Tools
  • What are Property Defaults
  • Live Reload
  • Automatic Restart
  • Remote Debugging

 

What is Dev Tools?

Spring Boot Dev Tools module was introduced in 1.3 to provide a powerful tool for the development.It helps developers to shorten the development cycle and enable easy deployment and testing during the development. In order to add use feature, we need to add a spring-boot-devtools dependency in our build. We need to add the following dependency to our Maven POM

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>

if you are using Gradle as your build tool

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

Once we perform build, spring-boot-devtools will be added to our project with its developer-friendly features. Let’s start exploring these features.

 

2. Property Defaults

Spring Boot comes with many production-ready features (Also known as auto-configuration) which include caching for its modules for performance. To boost performance, template engines might cache all compiled templates to avoid template parsing on each request. 

This is really helpful once we deploy our application on production but can be problematic during the development (We might not see changes immediately) e.g If you are using Thymeleaf with Spring Boot, you might be familiar with that Spring Boot automatically cache it.You can always control this by setting spring.thymeleaf.cache to false under application.properties.

With spring-boot-devtools, you don’t need to change this property manually but this module will do it automatically for you.

 

3. Automatic Restart

Typically as a development lifecycle, we make changes to our code, deploy it and test it and if things are not working as expected we will repeat this cycle. We can always use some third party tools like Jrebel to help in this (Jrebel check for the file change in the classpath ).

Spring Boot Dev Tools provide a similar feature (not as quick as Jrebel) to auto restart. Whenever a file changes in the classpath, spring-boot-devtools module will restart application automatically.

When you start your application with dev tools, you will find similar logs on the startup.

19:20:19.637 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
19:20:19.655 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
19:20:19.656 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/Users/target/classes/]

make some changes to your application code and perform build, an automatic restart will be triggered by spring-boot-devtools. Here are the logs from the restart

2017-12-18 19:25:11.111  INFO 31623 --- [      Thread-28] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot[email protected]7bc4b8cd: startup date [Mon Dec 18 19:20:20 PST 2017]; root of context hierarchy
2017-12-18 19:25:11.197  INFO 31623 --- [      Thread-28] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

Spring Boot use 2 class loader internally to handle this restart. we will be covering this feature in another post.

 

3.1 Exclusion

For certain resources, we really don’t need any restart (Think of change in static resources and templates), spring-boot-devtools will not trigger restart if you change resources at /META-INF/ resources, /resources, /static, /public, /template, if you want you can customize this behavior using spring.devtools.restart.exclude property.

 

3.2 Disable Restart

If you want to use the spring-boot-devtools module but like to disable restart feature, you can easily customize it by setting spring.devtools.restart.enabled in your application.properties file, you can disable this feature completely by setting this on the System property.

 public static void main(String[] args) {
        System.setProperty("spring.devtools.restart.enabled", "false");
        SpringApplication.run(DemoApplication.class, args);
    }

 

4. Live Reload

Spring Boot dev tools come with an embedded LiveReload server which will automatically trigger browser refresh when resource change. Visit  livereload.com for more information.

 

5. Remote Debugging via HTTP

Spring Boot dev tools provide ready to use remote debugging capabilities, in order to use this feature on the remote application, we have to make sure that devtools in included in the deployment packet. We can achieve this by setting the excludeDevtools property in our POM.xml file 

<plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludeDevtools>false</excludeDevtools>
            </configuration>
        </plugin>

 

In order to allow client to allow remote debugging, we need to make sure following steps

  • Start our application (Deployed on the server) with remote debugging enabled. This can be done by starting application with this additional parameters -Xdebug -Xrunjdwp:server=y,transport=dt_socket,suspend=n
  • System will automatically pick the free port (We have not given any port in our parameters)
  • Open Launch configurations with RemoteSpringApplication.
  • Default debug port for the system using spring-boot is 8080.
  • For debugging an application using IntelliJ. Please read Remote debug spring boot application with maven and IntelliJ

 

6. Remote Update

Spring Boot development tool also support update and restart for remote application. The remote client will monitor changes in the local classpath and will trigger a restart after pushing these changes to the remote server. This can be a handy feature if your work involves a cloud service.

 

 

6. Global Setting

The last feature of spring-boot-devtools is the ability to provide a global configuration which is not specific to any application.This can be achieved by adding a file named .spring-boot-devtools.properties in the $HOME.These configurations will be applicable to all the Spring Boot application on our machine.

 

Summary 

Spring Boot Dev Tools comes with many built-in features to help in the development lifecycle and make development experience better. We learned how to enabled by using these features provided under spring-boot-devtools modules.

Introduction to Java Loops

Introduction to Java Loops

Looping through an array or a collection is a very common day to day activity, in this post, we will get an introduction to Java Loops. We will be exploring various options for looping using Java.

 

Introduction

Looping is a feature which allows us to execute through a set of statements until our condition expression evaluates to false. Java provides multiple ways to Loop and choice is dependent upon the particular use case where we want to use it.

On a high level here are the options for Java Loops.

  1. for Loop
  2. While Loop
  3. Do-While Loop
  4. Enhanced for-each Loop

 

1. for Loop

A simple for loop which allows us to iterate over items until a specified condition is met or satisfied. This normally works with the help of a counter which will be initialized at the start of the execution and will be incremented with each iteration.

Based on the Java doc definition, a simple for loop have the following syntax

for (initialization; termination;increment) {
    statement(s)
}

Here are some of the important point to keep in mind while using simply for loop

  1. initialization will be done only once at the beginning of the loop.
  2. Loop will terminate when the termination condition will be evaluated as true.
  3. The increment is evaluated/ processed at each iteration.

 

Here is a very simple example

public class ForLoops {

    public static void main(String[] args) {

        for(int i=0 ;i<=6 ; i++){

            System.out.println("Value of i =" +i);
        }
    }
  
}

Output

Value of i =0
Value of i =1
Value of i =2
Value of i =3
Value of i =4
Value of i =5
Value of i =6

All three expressions for the for loop are optional which means you can easily create an infinite loop by removing all these expressions.

public class InfiniteForLoop {

    public static void main(String[] args) {

        //infinite loop by removing all expressions
        for(; ; ){

            System.out.println("Infinite Loop");
        }
    }
}

 

2. While Loop

As the name suggests, While loop will continually process statement or given code block while it’s evaluation expression is true.Here is an expression for while loop as per Java docs.

while (expression) {
    statement(s)
}

Here is a sample programme

public class WhileLoop {

    public static void main(String[] args) {

        int i = 0;

        while (i < 3) {
            System.out.println("Value of i = " + i);
            i++;
        }
    }
}

You can implement infinite while loop by setting expression as true 

public class WhileLoop {

    public static void main(String[] args) {
        while (true) {
          //your work
        }
    }
}

 

 

3. Do-While Loop

The do-while and while loop is similar and work in a similar way except that in a do-while loop, an expression is evaluated at the bottom as compared to the while loop.To put in another way, do block are always executed at least once.

public class DoWhileLoop {

    public static void main(String[] args) {

        int i = 0;
        do {
            System.out.println("Value of i = " + i);
            i++;
        } while (i < 5);
    }
}

 

4. Enhanced for Loop

Java 5 introduced a variation of the for loop known as enhanced for-loop.It provides a simple way to iterate over the elements of array/collection.Here is a syntax for the enhanced for loop

for(Type item : items){
    //Business rules
}

In order to use this loop, we only need to define following 2 things

  1. Type to hold element being iterated.
  2. Source of the iteration

We are no longer required to declare iteration index to loop through the element as this will be taken care internally by JDK. Here is an example demonstrating difference between simple for loop and enhanced for loop in Java

public class EnhancedForLoop {

    public static void main(String[] args) {
        
        List<String> stringList= Arrays.asList("One", "Two","Three");
        
        //in old for loop
        for(int i =0 ; i<= stringList.size() ; i++){
            System.out.println("List Value is "+stringList.get(i));
        }
        
        //with enhanced for loop
        for(String value : stringList){
            System.out.println("List Value is "+value);
        }
    }
}

 

4.1 Iterable.forEach()

We are already into Java 9 and it will not be good if we do not cover new enhancement introduced in Java 8.We have now a default method named forEach() added to the java.lang.Iterable<T> interface with an ability to accept lambda expressions.

Let’s take our earlier example and see how this can be redefined by utilizing new Java 8 feature

public class ForEachJava8 {

    public static void main(String[] args) {

        List<String> stringList= Arrays.asList("One", "Two","Three", "Four");

        //Before Java 8

        for(String value : stringList){

            //work will be done here
        }

        // With Java 8 and Lambda Expressions

        stringList.forEach(name -> System.out.println(name));

    }
}

As we saw, with introduction of Lambda Expression in Java 8, we were able to iterate through element using a single line of code

stringList.forEach(name -> System.out.println(name));

I will be covering benefits of Lambda and parallel execution in some other post.Read our article Lambda Expressions in Java to start with Java 8 Lambda Expressions.

Summary

In this post, we discussed different Java Loops. We covered new enhancement introduced in Java 5 for enhanced for loop along with the new features introduced with Java 8. You can download the examples from Github

What is Spring Boot

What is Spring Boot

This will be a short post more focused towards introducing Spring Boot, We will discussWhat is Spring Boot“? and how Spring Boot is helpful in building Java based enterprise applications.

 

Introduction

As a Java developer, it’s very likely that we have worked with Spring Framework based application directly or indirectly.Spring has a number of ways to configure its behavior, it provides the option to use XML based configurations or to use Annotations, JavaConfig is becoming the de facto standard for the new Spring based applications.Although these options seem really good, with large enterprise applications involves hundreds of modules and complicated business rules, these configurations can become really complicated. Below are some of the complications which large application can bring in to the picture

 

  • Each module has its own configurations.
  • Each module contains its own set of dependencies (third-party dependencies)
  • Upgrading application (e.g Spring 4.x to 5.x) will be complicated as we need to ensure that all required dependencies are upgraded correctly.
  • In case some of the dependencies are not working correctly, trying to find out root cause is a large application is really complicated and challenging.

 

All above issues are more or less related to making sure we have everything before dev team can start working on actual tasks. Now let’s talk about another use case which we use to do with any Spring based application, Let’s say we want to create a web-based application, these are most common steps most of us will be doing on regular basis

 

  • Create a web application using Maven or IDE of our choice.
  • Copy standard web application configurations (web.xml configuration for Spring MVC application).
  • Tweak above configurations based on our requirements.
  • Configure Spring MVC standard beans like ViewResolver, MessageSource etc.
  • Configure Database properties to be used for our application.
  • Establish DB layer and ensure underlying DB connection is in place before we can start using it (EntityManagerFactory, TransactionManager etc.)

 

This list can grow significantly based on type of our application

 

 

1. What is Spring Boot

All of the above steps seem very to us but they add a lot of overhead to the development team and instead of focusing on solving the actual business problem, initial time will be consumed to ensure that everything is in the correct place to start work. Think of Spring Boot as a tool which can do these initial tasks for us automatically.Spring Boot works on an opinionated view of the Spring platform being used by us and ensures that team can quickly start working on solving the actual business problem rather than spending time on the initial configurations and setup.

Spring Boot provides the following feature out of the box

    1. It simplifies Spring dependencies by taking the opinionated view ( we will discuss it in more details).
    2. Spring Boot provides a preconfigured set of technologies/framework to reduces error-prone configuration so we as a developer focused on building our business logic rather than thinking of project setup.
    3. You really don’t need those big XML configurations for your project.
    4. Embed Tomcat, Jetty or Undertow directly.
    5. Provide opinionated Maven POM to simplify your configuration

 

Using Spring Boot, it’s easy to manage and handle issues highlighted in the introduction section. .We are not required to manually search for compatible jars during upgrade,  Spring Boot will ensure that our application is upgraded to  the correct version (This is called working on application with minimum fuss)

Let’s take a look at a sample pom.xml for our web application to get an understanding of sample Spring Boot configuration

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javadevjournal.demo</groupId>
    <artifactId>sample web application</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
    </parent>
    <name>rWeb Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
</project>

Just pay close attention to <packaging> tag, Spring Boot provides flexibility to run our application as a jar and not forcing us to use war as required packaging type.

2. Better Dependency Management

Just check configuration closely and you won’t be finding any entry for all those Spring dependencies (like web MVC, core, AOP, ORM, Validation API etc.), you might have noticed similar entries spring-boot-starter-*, this is Spring Boot dependency management process. We have added spring-boot-starter-web to our pom.xml and Spring Boot will pull all required dependencies for Spring MVC application (no more manual configurations).

 

 

3. Auto Configurations

Auto Configuration is another interesting feature of Spring Boot this is why Spring Boot team say’s that it has opinions.These are some of work Spring Boot will do for you

  1. It will add all dependencies as highlighted in point 2.
  2. Auto Configurations indicates that Spring Boot has some reasonable defaults i.e based on the configurations Spring Boot will guess the type of application and will supply default implementations required to run your application in case we have not defined those in our application. in case you define these, Spring Boot will ensure that these defaults will be taken out of the context and let your custom configurations will take charge of application.
  3. To give a more clear picture, let’s say you have defined dependency for JPA and have not defined any database configurations, Spring Boot will automatically create required configurations for us. 

 

Read our article on to get the in-depth understanding of Spring Boot Auto Configurations.

 

 

3. Servlet Container

Do you recall that process of deploying your application on the Servlet container (Tomcat etc.), every time we make those small changes and require to deploy those into the app server to test our changes? Spring Boot provides support for embedded Servlet container and we are no longer require to deploy our application on app server (This can be run easily using standard main method) but at the same time we can access our application on the browser using http://<host>:<port>

Spring-boot-starter-web entry in our pom.xml will provide embedded servlet container for our web application, Apache Tomcat is the default servlet container provided by Spring Boot, however, Spring boot provides ways to use other servlet containers (all we have to add the required starter for this).

 

Read our post Building an Application with Spring Boot to start building your application with Spring Boot.

 

 

Summary

In this post, we get an understanding of the Spring Boot, we covered What is Spring Boot? and what are the Benefits of Spring Boot? We discussed different features of the Spring Boot. Spring Boot internally does a lot of things for us which seems to magical to us. In this series, we will be uncovering all these internal details of the Spring Boot.