Spring Boot Initializr with IDEs (via Spring Tool Suite)

Hello friends lets discuss another important components Spring Boot Initializr of Spring Boot, it is a quick way to create spring boot project structure. In this article we are going to explore about Spring Boot Initializr with STS IDE. Spring Boot Initializr is used to quick start new Spring Boot Maven/Gradle projects within no time. It generates initial project structure and builds scripts to reduce Development time.

Spring Tool Suite3 has long been a fantastic IDE for developing Spring applications. Since version 3.4.0 it has also been integrated with the Spring Initializr, making it a great way to get started with Spring Boot.

Related tutorials previously we have discussed

Create a new Spring Boot application in Spring Tool Suite


Step 1: Select the New > Spring Starter Project menu item from the File menu.

Step 2: We will get the following “Spring Starter Project” Wizard to provide our project related information.

Step 3: Please provide our Spring MVC Maven Web Application Project details as shown below and Click on “Next” Button

Step 4: Click on “Finish” button to create our new Spring Boot Project.

Step 5: Now Spring STS Suite creates a Maven Project and downloads all required Jars to our Maven Local Repository.

Step 6: Once the project has been imported into your workspace, you’re ready to start developing your application.

Step 7: Execute Spring Boot Application Run As > Spring Boot Application from the Run menu.

Step 8: Access our Spring MVC application with “http://localhost:8080/MySpringBootApp” and observe the results

SpringApplication:

The SpringApplication class provides a convenient way to bootstrap a Spring application that will be started from a main() method. In many situations you can just delegate to the static 
SpringApplication.run method:

  • SpringApplication is one of the Spring Boot API classes.
  • SpringApplication class is used to bootstrap a Spring application that will be started from a main() method
package com.dineshonjava;

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

@SpringBootApplication
public class MySpringBootAppApplication {

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

MySpringBootAppApplication class is annotated with @SpringBootApplication annotation.

@SpringBootApplication does the following things:

  • Because of @Configuration annotation, It scans for @Bean methods to create beans.
  • Because of @ComponentScan annotation, It does component scanning (Components means Beans annotated with @Component,@Service,@Repository,@Controller etc).
  • Because of @EnableAutoConfiguration annotation, It triggers Spring Boot Auto-Configuration.

When we run MySpringBootAppApplication class main() method, it make a calls to “SpringApplication.run()” method. Then this call done following things

  • This call is used to create “AnnotationConfigEmbeddedWebApplicationContext”.
  • This “AnnotationConfigEmbeddedWebApplicationContext” instance is used to create an instance of “TomcatEmbeddedServletContainerFactory” class.
  • This “TomcatEmbeddedServletContainerFactory” is used to create an instance of “TomcatEmbeddedServletContainer” class.
  • TomcatEmbeddedServletContainer” instance starts a Tomcat Container at default port number: 8080 and deploys our Spring Boot WebApplication.

Summary
Congratulation!!! Here we have learned how to create Spring Boot Application with Spring Boot Intilizr via STS IDE. And also discussed code flow of run this spring boot application.

Happy Spring Boot Learning!!!

Spring Boot Initializr Web Interface and Examples

Hello friends lets discuss another important components Spring Boot Initializr of Spring Boot, it is a quick way to create spring boot project structure. In this chapter we are going to explore about a web interface which create Spring Boot Application online.
Related tutorials previously we have discussed
What is Spring Boot Initializr?
The Spring Initializr is ultimately a web application (at “http://start.spring.io/”) that can generate a Spring Boot project structure for you. It doesn’t generate any application code, but it will give you a basic project structure and either a Maven or a Gradle build specification to build your code with.
Spring Initializr can be used in several ways:
  • Through a web-based interface
  • Via Spring Tool Suite
  • Via IntelliJ IDEA
  • Using the Spring Boot CLI
Why we need Spring Boot Initializr?
Sometimes the hardest part of a project is getting started. You need to set up a directory structure for various project artifacts, create a build file, and populate the build file with dependencies. The Spring Boot CLI removes much of this setup work, but if you favor a more traditional Java project structure, you’ll want to look at the Spring Initializr.
USING SPRING INITIALIZR’S WEB INTERFACE
Now we are starting with the web-based interface.
The Spring Team has provided a Web Interface for Spring Boot Initializr at “http://start.spring.io/”. We can use it to create our new Project’s base structure for Maven/Gradle build tools.
Creating Maven Example with Spring Boot Initializr Web Interface
There are following steps to create new Spring Boot Web Application for Maven Build tool and Spring STS Suite IDE.
Step 1: Go to Spring Boot Initializr at “http://start.spring.io/”.

Step 2: Once you’ve filled in the form and made your dependency selections, click the Generate Project button to have Spring Initializr generate a project for you.


Step 3: Now click on “Generate Project” Button, it creates and downloads a Maven Project as “myapp.zip” file into our local file system.

Step 4: Move “myapp.zip” to our Spring STS Suite Workspace and Extract this zip file
Step 5: Import this “myapp” Maven project into Spring STS IDE.
Step 6: We’d have a project structure similar.
If you observe this project files, it generates pom.xml file, two Spring Boot Java files and one JUnit Java file.
<?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.dineshonjava</groupId>
 <artifactId>myapp</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>myapp</name>
 <description>Demo project for Spring Boot</description>

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

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

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <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>
MyappApplication.java
package com.dineshonjava;

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

@SpringBootApplication
public class MyappApplication {

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

MyappApplicationTests.java
package com.dineshonjava;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyappApplication.class)
@WebAppConfiguration
public class MyappApplicationTests {

 @Test
 public void contextLoads() {
 }

}
Creating Gradle Example with Spring Boot Initializr Web Interface
All steps for creating gradle project with Spring Boot Initializr is same as like Maven Project as we have created above unlike select Gradle Project instead of Maven Project in Spring Boot Initializr Web Interface.

All source code files name and structure of project is also same as like maven project unlike creating build file name build.gradle instead of pom.xml
Spring Boot Initializr Web Interface and Examples
build.gradle
buildscript {
 ext {
  springBootVersion = '1.3.5.RELEASE'
 }
 repositories {
  mavenCentral()
 }
 dependencies {
  classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 
 }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot' 

jar {
 baseName = 'mygradleapp'
 version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
 mavenCentral()
}


dependencies {
 compile('org.springframework.boot:spring-boot-starter-data-jpa')
 compile('org.springframework.boot:spring-boot-starter-web')
 testCompile('org.springframework.boot:spring-boot-starter-test') 
}


eclipse {
 classpath {
   containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
   containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
 }
}

As you can see, there’s very little code in this project. Aside from a couple of empty directories, it also includes the following:
  • build.gradle—A Gradle build specification. Had you chosen a Maven project, this would be replaced with pom.xml.
  • Application.java—A class with a main() method to bootstrap the application.
  • ApplicationTests.java— an empty JUnit test class instrumented to load a Spring application context using Spring Boot auto-configuration.
  • application.properties—an empty properties file for you to add configuration properties to as you see fit.

Summary

Whether you use Initializr’s web-based interface, create your projects from Spring Tool Suite, or use the Spring Boot CLI to initialize a project, projects created using the Spring Boot Initializr have a familiar project layout, not unlike other Java projects you may have developed before.
Spring Boot is an exciting new way to develop Spring applications with minimal friction from the framework itself. Auto-configuration eliminates much of the boilerplate configuration that infests traditional Spring applications. Spring Boot starters enable you to specify build dependencies by what they offer rather than use explicit library names and version. The Spring Boot CLI takes Spring Boot’s frictionless development model to a whole new level by enabling quick and easy development with Groovy from the command line. And the Actuator lets you look inside your running application to see what and how Spring Boot has done.
Happy Spring Boot Learning!!!

Spring Boot CLI installation and Hello World Example

Hello friends!!! Welcome again for another Spring Boot tutorial. Here we are going to discuss more detail about Spring Boot CLI (Command Line Interface). Previously we have already discussed Introduction of Spring Boot and Essentials Key Components of Spring Boot. The quickest way to get started with Spring Boot is to install the Spring Boot CLI so that you can start writing code.
What is Spring Boot CLI?
The Spring Boot CLI is a command line tool that can be used if we want to quickly develop with Spring. It allows us to run Groovy scripts, which means that we have a familiar Java-like syntax, without so much boilerplate code. We can also bootstrap a new project or write your own command for it.
It is Spring Boot software to run and test Spring Boot applications from command prompt. When we run Spring Boot applications using CLI, then it internally uses Spring Boot Starter and Spring Boot AutoConfigurate components to resolve all dependencies and execute the application.
It internally contains Groovy and Grape (JAR Dependency Manager) to add Spring Boot Defaults and resolve all dependencies automatically.
Installing the Spring Boot CLI
There are several ways to install the Spring Boot CLI:
  • From a downloaded distribution
  • Using the Groovy Environment Manager
  • With OS X Homebrew
  • As a port using MacPorts
MANUALLY INSTALLING THE SPRING BOOT CLI
We can install Spring Boot CLI software using either Windows Installer or Zip file. Both approaches are easy to install and will give us same Spring Boot CLI software.
Step 1: You can download the Spring CLI distribution from the Spring software repository:
Once downloaded, follow the INSTALL.txt instructions from the unpacked archive. In summary: there is a spring script (spring.bat for Windows) in a bin/ directory in the .zip file, or alternatively you can use java -jar with the .jar file (the script helps you to be sure that the classpath is set correctly).
Step 2: Extract spring-boot-cli-1.4.0.BUILD-SNAPSHOT-bin.zip file into our local FileSystem.
Step 3: Set Spring Boot CLI Environment Variables in Windows System as shown below.
set PATH= D:personal datadojspring-1.4.0.BUILD-SNAPSHOTbin
Step 4: Execute the below command to verify our installation process.
Using the CLI
Once you have installed the CLI you can run it by typing spring.
We can use “spring –version” to know the Spring Boot CLI Version as shown below.
C:UsersDinesh>spring --version
Spring CLI v1.4.0.BUILD-SNAPSHOT

We can use “spring –help” to know the Spring Boot CLI Version as shown below.
C:UsersDinesh>spring --help
usage: spring [--help] [--version]
       <command> [<args>]

Available commands are:

  run [options] <files> [--] [args]
    Run a spring groovy script

  test [options] <files> [--] [args]
    Run a spring groovy script test
……..more command help is shown here
Now our Spring Boot CLI Installation process is done successfully.
Quick start Spring Boot CLI Hello World Example
Here we are using same example provided in Spring Boot Documentation.
Please follow the following steps to develop a Spring Boot HelloWorld Example:
Step 1: Create an “app” Folder in our Local FileSystem to place our groovy scripts.
Step 2: Create a file called app.groovy
@RestController
class app{
    @RequestMapping("/")
    String home() {
        "Hello World!"
    }
}
To compile and run the application type:
$ spring run app.groovy
To pass command line arguments to the application, you need to use a — to separate them from the “spring” command arguments, e.g.
$ spring run app.groovy — –server.port=9000
To set JVM command line arguments you can use the JAVA_OPTS environment variable, e.g.
$ JAVA_OPTS=-Xmx1024m spring run app.groovy
Observation on Code:
If we observe our app.groovy, we can find the following important points.
  • No imports
  • No other XML configuration to define Spring MVC Components like Views,ViewResolver etc.
  • No web.xml and No DispatcherServlet declaration
  • No build scripts to create our Application war file
  • No need to build war file to deploy this application
Now for running the application
Open command prompt at “app” Folder in our Local FileSystem.
Execute the following command
spring run app.groovy
Observe the output at “spring run” command console.
If we observe here, when we execute “spring run app.groovy”, it starts Embedded Tomcat server at Default port number: 8080.
Now our Spring Boot HelloWorld Example application is up and running. It’s time to test it now.
In the above example we can observe following points.
  • There is no Import
  • There is no XML or JAVA configuration
  • There is no DispatcherServlet and web.xml
  • There is no build file for creating war like Maven or Gradle

It is the responsibility of Spring Boot Core Components, Groovy Compiler (groovyc) and Groovy Grape (Groovy’s JAR Dependency Manager).
Spring Boot Components uses Groovy Compiler and Groovy Grape to provide some Defaults lime adding required imports, providing required configuration, resolving jar dependencies, adding main() method etc. As a Spring Boot Developer, We don’t need to worry all these things. Spring Boot Framework will take care of all these things for us.
That’s the beauty of Spring Boot Framework.
Default import statements
To help reduce the size of your Groovy code, several import statements are automatically included. Notice how the example above refers to @Component,@RestController and @RequestMapping without needing to use fully-qualified names or import statements.
Automatic main method
Unlike the equivalent Java application, you do not need to include a public static void main(String[] args) method with your Groovy scripts. ASpringApplication is automatically created, with your compiled code acting as the source.

Summary

The Spring Boot CLI takes the simplicity offered by Spring Boot auto-configuration and starter dependencies and turns it up a notch. Using the elegance of the Groovy language, the CLI makes it possible to develop Spring applications with minimal code noise.

Happy Spring Boot Learning!!!

Essentials and Key Components of Spring Boot

Hello friends welcome for this tutorial. In line of Spring Boot tutorials we have already discussed “Introduction to Spring Boot – A Spring Boot Complete Guide” here about Spring Boot basics. Now we will discuss about “What are the essentials components of Spring Boot”.

Essentials and Internals of Spring Boot:

Spring Boot gives us a great deal of magic to Spring application development. But there are four core essentials or key components that it performs:
  • Spring Boot Starters- We just tell Spring Boot what kind of functionality we need; now it is responsibility of Spring Boot so that it will ensure that the libraries needed are added to the build.
  • Spring Boot AutoConfigurator- Spring Boot can automatically provide configuration for application functionality common to many Spring applications.
  • Spring Boot CLI- This optional feature of Spring Boot lets you write complete applications with just application code, but no need for a traditional project build.
  • Spring Boot Actuator- Gives us insight of application into what’s going on inside of a running Spring Boot application.

Each of these key components serves to simplify Spring application development in its own way. There are two ways for creating Spring Boot application or help to create spring boot application.

  • Spring Initializr- To quick start new Spring Boot projects, we can use “Spring Initializr” web interface. Spring Initializr URL: http://start.spring.io.
  • Spring Boot IDEs- We has many Spring Boot IDEs like Eclipse IDE, IntelliJ IDEA, Spring STS Suite etc.

1. Spring Boot Starters

When we start to working with a spring project then it can be challenging to add dependencies to a project’s build. What libraries do you need? What are its group and artifact? Which version do you need? Will that version play well with other dependencies in the same project?

Spring Boot Starters is one of the major key features or components of Spring Boot. Spring Boot offers help with project dependency management by way of starter dependencies. The main responsibility of Spring Boot Starter is to combine a group of common or related dependencies into single dependencies.

For example, suppose that we’re going to build a REST API with Spring MVC that
works with JSON resource representations. To accomplish all of this, you’ll need (at minimum) the following four dependencies in your Maven or Gradle build:

  • org.springframework:spring-core
  • org.springframework:spring-web
  • org.springframework:spring-webmvc
  • com.fasterxml.jackson.core:jackson-databind

Additionally, you want to apply declarative validation per the JSR-303 specification and serve the application using an embedded Tomcat server. Then we have added four more dependencies as below:

  • org.hibernate:hibernate-validator
  • org.apache.tomcat.embed:tomcat-embed-core
  • org.apache.tomcat.embed:tomcat-embed-el
  • org.apache.tomcat.embed:tomcat-embed-logging-juli

It is very tedious and cumbersome tasks for a Developer. And also it increases our build file size. What is the solution to avoid this much dependencies definitions in our build files? The solution is Spring Boot Starter component.

On the other hand, we are using Spring Boot Starter Component; it combines all related jars into single jar file so that we can add only one jar file dependency to our build files. If we were to take advantage of Spring Boot starter dependencies, We could simply add the Spring Boot “web” starter (org.springframework.boot:spring-boot-starter-web) as a build dependency. This single dependency will transitively pull in all of those other dependencies so you don’t have to ask for them all.

One thing we have to notice that by adding the “web” starter to our build, we’re specifying a type of functionality that your application needs. Here our app is a web application, so we add the “web” starter. Likewise, if our application will use JPA persistence, then we can add the “jpa” starter. If it needs security, we can add the “security” starter. In short, we no longer need to think about what libraries we’ll need to support certain functionality; we simply ask for that functionality by way of the pertinent starter dependency. Also note that Spring Boot’s starter dependencies free us from worrying about which versions of these libraries we need.

Major Advantages of Spring Boot Starter

  • Spring Boot Starter reduces defining many dependencies simplify project build dependencies.
  • Spring Boot Starter simplifies project build dependencies.
  • Spring Boot Starter sync version compatibilities of dependencies.

2. Spring Boot AutoConfigurator
There is one of them important key component of Spring Boot is Spring Boot AutoConfigurator. In any given Spring application’s source code, we’ll find either Java configuration or XML configuration (or both) that enables certain supporting features and functionality for the application that is why it requires lot of configuration (either Java configuration or XML configuration).

The main responsibility of Spring Boot AutoConfigurator is to reduce the Spring Configuration. If we develop Spring applications in Spring Boot, then We don’t need to define single XML configuration and almost no or minimal Annotation configuration. Spring Boot AutoConfigurator component will take care of providing that information.

For example, if we’ve ever written an application that accesses a relational database with JDBC, we’ve probably configured Spring’s JdbcTemplate as a bean in the Spring application context. I’ll bet the configuration looked a lot like this:

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
This very simple bean declaration creates an instance of JdbcTemplate, injecting it with its one dependency, a DataSource. Of course, that means that we’ll also need to configure a DataSource bean so that the dependency will be met. To complete this configuration scenario, suppose that we were to configure an embedded H2 database as the DataSource bean:
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScripts('schema.sql', 'data.sql')
.build();
}

This bean configuration method creates an embedded database, specifying two SQL scripts to execute on the embedded database. The build() method returns a Data-Source that references the embedded database.

Neither of these two bean configuration methods is terribly complex or lengthy. But they represent just a fraction of the configuration in a typical Spring application. Moreover, there are countless Spring applications that will have these exact same methods. Any application that needs an embedded database and a JdbcTemplate will need those methods. In short, it’s boilerplate configuration.

If it’s so common, then why should you have to write it? The solution to this problem is Spring Boot AutoConfigurator.

And also Spring Boot reduces defining of Annotation configuration. If we use @SpringBootApplication annotation at class level, then Spring Boot AutoConfigurator will automatically add all required annotations to Java Class ByteCode.

Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication

That is, @SpringBootApplication = @Configuration + @ComponentScan + @EnableAutoConfiration.

Note- in Shot, Spring Boot Starter reduces build’s dependencies and Spring Boot AutoConfigurator reduces the Spring Configuration.

3. Spring Boot CLI

In addition to auto-configuration and starter dependencies, Spring Boot also offers an intriguing new way to quickly write Spring applications. Spring Boot’s CLI leverages starter dependencies and auto-configuration to let us focus on writing code. When we run Spring Boot applications using CLI, then it internally uses Spring Boot Starter and Spring Boot AutoConfigurate components to resolve all dependencies and execute the application.

Spring Boot’s CLI is an optional piece of Spring Boot’s power. Although it provides tremendous power and simplicity for Spring development, it also introduces a rather unconventional development model.

Spring Boot CLI has introduced a new “spring” command to execute Groovy Scripts from command prompt.

spring run app.groovy
Spring Boot CLI component requires many steps like CLI Installation, CLI Setup, Develop simple Spring Boot application and test it.

4. Spring Boot Actuator
The final key component of the Spring Boot is the Actuator. Where the other parts of Spring Boot simplify Spring development, the Actuator instead offers the ability to inspect the internals of your application at runtime. Spring Boot Actuator components gives many features, but two major features are

  • Providing Management EndPoints to Spring Boot Applications.
  • Spring Boot Applications Metrics.

The Actuator exposes this information in two ways: via web endpoints or via a shell interface.

We inspect the inner workings of your application with Actuator as below:

  • What beans have been configured in the Spring application context
  • What decisions were made by Spring Boot’s auto-configuration
  • What environment variables, system properties, configuration properties, and command-line arguments are available to your application
  • The current state of the threads in and supporting your application
  • A trace of recent HTTP requests handled by your application
  • Various metrics pertaining to memory usage, garbage collection, web requests, and data source usage

When we run our Spring Boot Web Application using CLI, Spring Boot Actuator automatically provides hostname as “localhost” and default port number as “8080”. We can access this application using “http://localhost:8080/” end point.

We actually use HTTP Request methods like GET and POST to represent Management EndPoints using Spring Boot Actuator.

Summary
Congratulation!!! today we have learned about key components of Spring Boot. That’s it about Spring Components and Internals. We will discuss about these components in details with some Spring Boot examples in coming posts.

Happy Spring Boot Learning!!!

Spring Boot Tutorial Best Complete Introduction

Spring Boot

Hello friends today I am going to discuss one of the latest innovation by the Spring Team (Pivotal Team) is Spring Boot, oops… sorry..friends yes I know I am late for this discussion right now but it is not too late for spring boot because this is actual time for major adoption of Spring Boot for scratch project in the spring framework 🙂. If you are already familiar with spring framework then it is too easy to learn because Spring Boot is nothing but it developed on top of existing Spring Framework. It uses completely new development model to make Java Development very easy by avoiding some tedious development steps and boilerplate code and configuration.

Table of Contents

  1. Introducing to Spring Boot
  2. What is Spring Boot?
  3. Spring Boot Primary Goals
  4. Why New Project Need Spring Boot?
  5. What Spring Boot isn’t
  6. Pros/Cons of Spring Boot
  7. Spring boot releases
  8. Getting started with Spring
  9. Hello World example using spring boot
  10. Starter POMs
  11. Servlet containers support
  12. Template Engines Support
  13. Caching Support
  14. Spring Boot & Spring MVC
  15. Spring boot tutorials
  16. Videos
  17. Adoption
  18. Summary
1. Introducing to Spring Boot
Spring Team has released one of major innovation on the top of existing Spring Framework is Spring Boot.  It is a completely new project from Pivotal Team (The Spring Team). Spring Boot is their latest innovation to keep up to date with the changing technology needs. The primary motivation behind developing Spring Boot is to simplify the process for configuring and deploying the spring applications.

Spring Boot offers a new paradigm for developing Spring applications with minimal friction. With Spring Boot, you’ll be able to develop Spring applications with more agility and be able to focus on addressing your application’s functionality needs with minimal (or possibly no) thought of configuring Spring itself. It uses completely new development model to make Java Development very easy by avoiding some tedious development steps and boilerplate code and configuration.

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. We take an opinionated view of the spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
You can use Spring Boot to create Java applications that can be started using java -jar or more traditional war deployments. We also provide a command line tool that runs “spring scripts”.

2. What is spring boot?
First of all Spring Boot is not a framework, it is a way to ease to create stand-alone application with minimal or zero configurations. It is approach to develop spring based application with very less configuration. It provides defaults for code and annotation configuration to quick start new spring projects within no time. It leverages existing spring projects as well as Third party projects to develop production ready applications. It provides a set of Starter Pom’s or gradle build files which one can use to add required dependencies and also facilitate auto configuration.

Spring Boot automatically configures required classes depending on the libraries on its classpath. Suppose your application want to interact with DB, if there are Spring Data libraries on class path then it automatically sets up connection to DB along with the Data Source class.
Spring Boot

3. Spring Boot Primary Goals
Spring Boot primary goals are:
  • Provide a radically faster and widely accessible getting started experience for all Spring development.
  • Be opinionated out of the box, but get out of the way quickly as requirements start to diverge from the defaults.
  • Provide a range of non-functional features that are common to large classes of projects (e.g. embedded servers, security, metrics, health checks, externalized configuration).
  • Absolutely no code generation and no requirement for XML configuration, to avoid XML Configuration completely
  • To avoid defining more Annotation Configuration(It combined some existing Spring Framework Annotations to a simple and single Annotation)
  • To avoid writing lots of import statements
  • To provide some defaults to quick start new projects within no time.
4. Why New Project Need Spring Boot?
Suppose we are developing one of Hello World application in Spring Framework, for that there is only one item is specific to developing the Hello World functionality: the controller. The rest of it is generic boilerplate that you’d need for any web application developed with Spring. But if all Spring web applications need it, why should you have to provide it? So there are following things any new project need Spring Boot.
  • To ease the Java-based applications Development, Unit Test and Integration Test Process.
  • To reduce Development, Unit Test and Integration Test time by providing some defaults.
  • To increase Productivity.
  • When we talk about defaults, Spring Boot has its own opinions. If you are not specifying the details, it will use its own default configurations. If you want persistence, but don’t specify anything else in your POM file, then Spring Boot configures Hibernate as a JPA provider with an HSQLDB database.
  •  To provide bunch of non-functional features/solutions that are very much common to large scale projects (e.g. embedded servers, security, metrics, health checks, externalized configuration).
5. What Spring Boot Isn’t?
As above mention Spring Boot is not a framework to write applications, it helps you to develop and build, package and deploy application with minimal configuration or zero configuration.
It is not an application server. But it’s the embedded servlet container that provides application server functionality, not Spring Boot itself.
Similarly, Spring Boot doesn’t implement any enterprise Java specifications such as JPA or JMS. For example, Spring Boot doesn’t implement JPA, but it does support JPA by auto-configuring the appropriate beans for a JPA implementation (such as Hibernate)
Finally, Spring Boot doesn’t employ any form of code generation to accomplish its magic. Instead, it leverages conditional configuration features from Spring 4, along with transitive dependency resolution offered by Maven and Gradle, to automatically configure beans in the Spring application context.
In short, at its heart, Spring Boot is just Spring.

Future Spring projects would not have any XML configurations as part of it, everything will be handled by the project Spring Boot.

spring certification
6. Pros/Cons of Spring Boot
    Pros of Spring Boot:

  • It is very easy to develop Spring Based applications with Java or Groovy.
  • It reduces lots of development time and increases productivity.
  • It avoids writing lots of boilerplate Code, Annotations and XML Configuration.
  • It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.
  • It follows “Opinionated Defaults Configuration” Approach to reduce Developer effort
  • It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.
  • It provides CLI (Command Line Interface) tool to develop and test Spring Boot (Java or Groovy) Applications from command prompt very easily and quickly.
  • It provides lots of plugins to develop and test Spring Boot Applications very easily using Build Tools like Maven and Gradle
  • It provides lots of plugins to work with embedded and in-memory Databases very easily.
Limitation of Spring Boot:
It is very tough and time consuming process to convert existing or legacy Spring Framework projects into Spring Boot Applications. It is applicable only for brand new/Greenfield Spring Projects.
7. Spring boot releases
Latest Release: Spring Boot 1.3.3 and 1.4.0 available now. You require minimum Spring Framework 4.2.2 for this version.
  • ·        Executable JAR Layout
  • ·        Startup error improvements
  • ·        Hibernate 5
  • ·        Spring Framework 4.3
  • ·        Third Party Library
  • ·        Custom JSON Serializer and Deserializer
  • ·        New auto-configuration support
    • o   Couchbase
    • o   Neo4j
    • o   Narayana transactional manager
    • o   Caffeine Cache
  • ·        Actuator improvements
  • ·        Testing improvements

8. Getting started with Spring Boot

Ultimately, a Spring Boot project is just a regular Spring project that happens to leverage Spring Boot starters and auto-configuration. To Start Opinionated Approach to create Spring Boot Applications, The Spring Team (The Pivotal Team) has provided the following three approaches.
We can develop two flavors of Spring-Based Applications using Spring Boot
  • Java-Based Applications
  • Groovy Applications
We can use Spring Boot CLI or Spring STS IDE or Spring Initializr Website to develop Spring Boot Groovy Applications. However, we can use Spring STS IDE or Spring Initializr Website to develop Spring Boot Java Applications.

Anyhow, Groovy is also JVM language almost similar to Java Language. We can combine both Groovy and Java into one Project. Because like Java files, Groovy files are finally compiled into *.class files only. Both *.groovy and *.java files are converted to *.class file (Same byte code format).
Spring Boot Framework Programming model is inspired by Groovy Programming model. Spring Boot internally uses some Groovy based techniques and tools to provide default imports and configuration.
Spring Boot Framework also combined existing Spring Framework annotations into some simple or single annotations. We will explore those annotations one by one in coming posts with some real-time examples.
Spring Boot Framework drastically changes Spring-Java Based Applications Programming model into new Programming model. As of now, Spring Boot is at initial stage only but future is all about Spring Boot only.

Spring Boot CLI
It is the easiest and quickest way to start using the Spring Boot. It is a command line tool used for executing the groovy scripts. In summary, you can install this tool by following these steps:
1.     Download the binary distributions for this project from here. Spring Boot CLI requires Java JDK v1.6 or above in order to run. Groovy v2.1 is packaged as part of this distribution, and therefore does not need to be installed (any existing Groovy installation is ignored)
2.     If you unpack the zip file, you will find spring.bat which will check the all the settings. This script can be found under the directory /bin.
9. Hello World example using spring boot
We can develop two flavors of Spring-Based Applications using Spring Boot.
  • Groovy Applications
  • Java-Based Applications
Groovy Applications:

Let’s develop a simple “Hello World!” web application. Create the app.groovy with the following lines of code. Here we are going explain same example from Spring Boot documentation.

@RestController
class ThisWillActuallyRun {

    @RequestMapping("/")
    String home() {
        return "Hello World!"
    }

}

Run it as follows:

$ spring run app.groovy

You can invoke the http://localhost:8080 in your browser and you will see the result “Hello World!”.The above command can invoke the application and run it in the web server.

Spring Boot does this by dynamically adding key annotations to your code and leveraging Groovy Grape to pull down needed libraries to make the app run. If any dependencies are required like web server, etc. can be resolved by the Spring Boot itself.
Java-Based Applications
Let’s develop a simple “Hello World!” web application in Java that highlights some of Spring Boot’s key features. We’ll use Maven to build this project since most IDEs support it.
If you are Java developer you can use start.spring.io to generate a basic project.
Build with Maven
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.doj</groupId>
    <artifactId>my-spring-boot-project</artifactId>
    <version>0.0.1-SNAPSHOT </version>

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

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

    <properties>
        <java.version>1.8</java.version>
    </properties>


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

</project>

Once maven is in the class path, it is very easy to create a maven project and run the example. Just create a Java file with the below code snippet:

package hello;

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

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

Once you have created the above Java file and the pom.xml in the same directory, please run the following command:
$ mvn package
$ java -jar target/ my-spring-boot-project-0.0.1-SNAPSHOT.jar

First statement invokes the pom.xml and builds the complete package by downloading all the dependencies. The second statement makes the spring application and bundle with the web server. As said in the above groovy example, you can invoke the application in the browser.
10. Starters
Starters are a set of convenient dependency descriptors that you can include in your application. The starters contain a lot of the dependencies that you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies.
The starter POMs are convenient dependency descriptors that can be added to your application’s Maven. In simple words, if you are developing a project that uses Spring Batch for batch processing, you just have to include spring-boot-starter-batch that will import all the required dependencies for the Spring Batch application. This reduces the burden of searching and configuring all the dependencies required for a framework.

Spring offers wide range of started POMs that can be used in your application. Here is the list of started POMs.
Name
Description
Pom
spring-boot-starter-test Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito Pom
spring-boot-starter-mobile Starter for building web applications using Spring Mobile Pom
spring-boot-starter-social-twitter Starter for using Spring Social Twitter Pom
spring-boot-starter-cache Starter for using Spring Framework’s caching support Pom
spring-boot-starter-activemq Starter for JMS messaging using Apache ActiveMQ Pom
spring-boot-starter-jta-atomikos Starter for JTA transactions using Atomikos Pom
spring-boot-starter-aop Starter for aspect-oriented programming with Spring AOP and AspectJ Pom
spring-boot-starter-web Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container Pom
spring-boot-starter-data-elasticsearch Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch Pom
spring-boot-starter-jdbc Starter for using JDBC with the Tomcat JDBC connection pool Pom
spring-boot-starter-batch Starter for using Spring Batch, including HSQLDB in-memory database Pom
spring-boot-starter-social-facebook Starter for using Spring Social Facebook Pom
spring-boot-starter-web-services Starter for using Spring Web Services Pom
spring-boot-starter-jta-narayana Spring Boot Narayana JTA Starter Pom
spring-boot-starter-thymeleaf Starter for building MVC web applications using Thymeleaf views Pom
spring-boot-starter-mail Starter for using Java Mail and Spring Framework’s email sending support Pom
spring-boot-starter-jta-bitronix Starter for JTA transactions using Bitronix Pom
spring-boot-starter-data-mongodb Starter for using MongoDB document-oriented database and Spring Data MongoDB Pom
spring-boot-starter-validation Starter for using Java Bean Validation with Hibernate Validator Pom
spring-boot-starter-jooq Starter for using jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc Pom
spring-boot-starter-redis Starter for using Redis key-value data store with Spring Data Redis and the Jedis client. Deprecated as of 1.4 in favor of spring-boot-starter-data-redis Pom
spring-boot-starter-data-cassandra Starter for using Cassandra distributed database and Spring Data Cassandra Pom
spring-boot-starter-hateoas Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS Pom
spring-boot-starter-integration Starter for using Spring Integration Pom
spring-boot-starter-data-solr Starter for using the Apache Solr search platform with Spring Data Solr Pom
spring-boot-starter-freemarker Starter for building MVC web applications using Freemarker views Pom
spring-boot-starter-jersey Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web Pom
spring-boot-starter Core starter, including auto-configuration support, logging and YAML Pom
spring-boot-starter-data-couchbase Starter for using Couchbase document-oriented database and Spring Data Couchbase Pom
spring-boot-starter-artemis Starter for JMS messaging using Apache Artemis Pom
spring-boot-starter-cloud-connectors Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku Pom
spring-boot-starter-social-linkedin Stater for using Spring Social LinkedIn Pom
spring-boot-starter-velocity Starter for building MVC web applications using Velocity views. Deprecated since 1.4 Pom
spring-boot-starter-data-rest Starter for exposing Spring Data repositories over REST using Spring Data REST Pom
spring-boot-starter-data-gemfire Starter for using GemFire distributed data store and Spring Data GemFire Pom
spring-boot-starter-groovy-templates Starter for building MVC web applications using Groovy Templates views Pom
spring-boot-starter-amqp Starter for using Spring AMQP and Rabbit MQ Pom
spring-boot-starter-hornetq Starter for JMS messaging using HornetQ. Deprecated as of 1.4 in favor of spring-boot-starter-artemis Pom
spring-boot-starter-ws Starter for using Spring Web Services. Deprecated as of 1.4 in favor of spring-boot-starter-web-services Pom
spring-boot-starter-security Starter for using Spring Security Pom
spring-boot-starter-data-redis Starter for using Redis key-value data store with Spring Data Redis and the Jedis client Pom
spring-boot-starter-websocket Starter for building WebSocket applications using Spring Framework’s WebSocket support Pom
spring-boot-starter-mustache Starter for building MVC web applications using Mustache views Pom
spring-boot-starter-data-neo4j Starter for using Neo4j graph database and Spring Data Neo4j Pom
spring-boot-starter-data-jpa Starter for using Spring Data JPA with Hibernate Pom

11. Servlet containers Support
The following embedded servlet containers are supported out of the box.
Name
Servlet Version
Java Version
Tomcat 8
3.1
Java 7+
Tomcat 7
3.0
Java 6+
Jetty 9
3.1
Java 7+
Jetty 8
3.0
Java 6+
Undertow 1.1
3.1
Java 7+
You can also deploy Spring Boot applications to any Servlet 3.0+ compatible container.

12. Template engines Support

Spring Boot includes auto-configuration support for the following templating engines

·         FreeMarker

·         Groovy

·         Thymeleaf

·         Velocity (deprecated in 1.4)

·         Mustache

JSPs should be avoided if possible; there are several known limitations when using them with embedded servlet containers. If you are using any of the above template engines, spring boot will automatically pick the templates from src/main/resources/templates.

13. Caching Support

The Spring Framework provides support for transparently adding caching to an application. At its core, the abstraction applies caching to methods, reducing thus the number of executions based on the information available in the cache. The caching logic is applied transparently, without any interference to the invoker.

import javax.cache.annotation.CacheResult;

import org.springframework.stereotype.Component;

@Component
public class MathService {

    @CacheResult
    public int computePiDecimal(int i) {
        // ...
    }

}

Spring Boot tries to detect the following providers (in this order):

·         Generic

·         JCache (JSR-107)

·         EhCache 2.x

·         Hazelcast

·         Infinispan

·         Couchbase

·         Redis

·         Caffeine

·         Guava

·         Simple

14. Spring Boot & Spring MVC

Spring Boot is well suited for web application development. You can easily create a self-contained HTTP server using embedded Tomcat, Jetty, or Undertow. Most web applications will use the spring-boot-starter-web module to get up and running quickly.

Spring MVC lets you create special @Controller or @RestController beans to handle incoming HTTP requests. Methods in your controller are mapped to HTTP using @RequestMapping annotations.

Spring MVC auto-configuration

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.The auto-configuration adds the following features on top of Spring’s defaults:
  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
  • Support for serving static resources, including support for WebJars (see below).
  • Automatic registration of Converter, GenericConverter, Formatter beans.
  • Support for HttpMessageConverters (see below).
  • Automatic registration of MessageCodesResolver (see below).
  • Static index.html support.
  • Custom Favicon support.
  • Automatic use of a ConfigurableWebBindingInitializer bean

15. Spring boot tutorials

Spring Boot Related Topics

  1. Spring Boot Interview Questions and Answers
  2. Introduction to Spring Boot
  3. Essentials and Key Components of Spring Boot
  4. Spring Boot CLI Installation and Hello World Example
  5. Spring Boot Initializr Web Interface
  6. Spring Boot Initializr With IDEs
  7. Spring Boot Initializr With Spring Boot CLI
  8. Installing Spring Boot
  9. Developing your first Spring Boot application
  10. External Configurations for Spring Boot Applications
  11. Logging Configuration in Spring Boot
  12. Spring Boot and Spring MVC
  13. Working with SQL Databases and Spring Boot
  14. MySQL Configurations
  15. Spring Data JPA using Spring Boot Application
  16. Spring Boot with NoSQL technologies
  17. Spring Cache Tutorial
  18. Spring Security Tutorial with Spring Boot
  19. Spring Boot and MongoDB in REST Application
  20. Complete Guide for Spring Boot Actuator
  21. Microservices with Spring Boot
16. Videos

Here is the one good video on Spring Book introduction by Josh Long

17. Spring Boot Adoption
Adoption in March 2016
Eugen has published his original report here.

In March of 2016, 81.1% of Spring users are using Spring 4 – so definitely a lot of growth since last year’s 65%:

Spring Boot is even more interesting, growing from 34% last year to 52.8%:
Spring Boot Adoption in 2015

Eugen has published a report about the Spring Boot adoption here. This chart shows that there is more developers started using Spring Boot for their project development.

18. Summary

Congratulations! You have learned Spring Boot introduction and some essentials points of it and built a simple web application with Spring Boot and learned how it can ramp up your development pace. You also turned on some handy production services. This is only a small sampling of what Spring Boot can do. Checkout SpringBoot’s online docs if you want to dig deeper.
Happy Spring Boot Framework Learning!

New Features in Spring Boot 1.4

On Last month May 17, 2016 spring boot team has announced the release of Spring Boot 1.4.0 M3. There is lot of changes coming up in the new release. In this post I am going to list down the summary of new features in spring boot 1.4 This release closes over 150 issues and introduces a number of new features.

Highlights include:

  • Lots of bug fixes and improvements over M2 (thanks to everyone for trying the milestones).
  • Convention based error pages (want a custom 404, just add src/main/resources/public/error/404.html).
  • Improved ErrorPage registration support.
  • Support for pluggable OAuth2 Principal extraction.
New Features in Spring Boot 1.4
There are following new features of Spring Boot 1.4 Version release
  1. Executable JAR Layout
  2. Startup error improvements
  3. Hibernate 5
  4. Spring Framework 4.3
  5. Third Party Library
  6. Custom JSON Serializer and Deserializer
  7. New auto-configuration support
    1.     Couchbase
    2.     Neo4j
    3.     Narayana transactional manager
    4.     Caffeine Cache
  8. Actuator improvements
  9. Testing improvements
  10. Datasource binding
  11. Image Banner
  12. Summary

Executable JAR Layout
If you are building the JAR file as an executable spring boot application, all the dependencies will be packaged under WEB-INF/lib and application’s own classes will be packages under root of the JAR file. But, spring boot 1.4.0 will package the dependencies under BOOT-INF/lib and application’s own classes under BOOT-INF/classes.

Startup Error Improvements
There is a improvement in displaying the useful error description on startup failures. Prior to 1.4.0, startup failures shows long stack trace that would not show the actual issue unless developer has to read the complete stack trace. But, latest release just shows the cause of the failure and what is the solution.

Hibernate 5

If you have upgrade problems switching to Hibernate 5 can be postponed at a later stage by setting the hibernate.version in your pom.xml. Note though that the Spring team will not support Hibernate 4.3 from Spring Boot 1.4. So, it is advisable to upgrade to the latest hibernate versions immediately.
If you want to still use the older version in your application, please add the following entries in your pom.xml:
<properties>
 <hibernate.version>4.3.11.Final</hibernate.version>
</properties>

Spring 4.3.0-RC1
In Spring 4.3.0-RC1 there are lots of new features and enhancements. The full list you can find it here. (Also Read : Spring 4 Tutorials).

Third Party Libraries

  • Hibernate 5.1
  • Jackson 2.7
  • Solr 5.5
  • Spring Data Hopper
  • Spring Session 1.2
  • Hazelcast 3.6.

Custom JSON Serializer and Deserializer
If you want to register a bean as the JSON components, then you can use @JsonComponent annotation as below:

@JsonComponent
public class ModelData{
....
}

New Auto-Configuration Support
Spring boot adds new auto configuration modules for every release. In this release also there are few more modules added to support the auto-configurations.

  • Couchbase
  • Neo4j
  • Narayana Transaction Manager
  • Caffeine Cache

Actuator Improvements

There is a slight improvements on info endpoint information and metrics filter.
Now you can register the InfoContributor interface to register the beans that expose the information to the info actuator endpoints.

The support provided for:

  • Full or partial Git information generated from a build plugin
  • Build information generated from the Spring Boot Maven or Gradle plugin.
  • Custom information from the Environment (any property starting info.*)

Testing support
The biggest change comes regarding testing support. There are two new modules spring-boot-test and spring-boot-test-autoconfigure

@SpringBootTest

Spring already comes with great support for writing integration tests leveraging the spring-test module. The only problem might be that it uses lots of annotations (@SpringApplicationConfiguration, @ContextConfiguration, @IntegrationTest, @WebIntegrationTest) to accomplish it.

Spring Boot 1.4 tries to simplify this by providing a single @SpringBootTest annotation.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Sql("/init-for-full-integration-test.sql")
public class ApplicationTests {

 @Autowired
 private TestRestTemplate template;

 @Test
 public void random() {
  ResponseEntity<String> fact = template.getForEntity("/", String.class);

  assertThat(fact.getBody(), containsString("Chuck Norris sleeps with a pillow under his gun."));
 }
}

Here as you can see for convenience the injected TestRestTemplate is already configured to make calls against the started server, no need to inject the port with @Value(“${local.server.port}”). However if you would like to know the port there is a better @LocalServerPort annotation.

Testing slices of the application
Sometimes you would like to test a simple “slice” of the application instead of auto-configuring the whole application. Spring Boot 1.4 introduces 3 new test annotations:

  • @WebMvcTest – for testing the controller layer
  • @JsonTest – for testing the JSON marshalling and unmarshalling
  • @DataJpaTest – for testing the repository layer

@WebMvcTest
In order to test only the controller layer or often a single controller the @WebMvcTest used in combination with @MockBean can be handy. @Service or @Repository components will not be scanned.

@RunWith(SpringRunner.class)
@WebMvcTest(ChuckNorrisFactController.class)
public class CheckNorrisFactControllerTests {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private ChuckNorrisFactService chuckNorrisFactService;

    @Test
    public void getOneRandomly() throws Exception {
        given(chuckNorrisFactService.getOneRandomly()).willReturn(new ChuckNorrisFact("Chuck Norris counted to infinity twice."));

        mvc.perform(get("/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().json("{'fact':'Chuck Norris counted to infinity twice.'}"));
    }
}

@JsonTest
To test JSON marshalling and unmarshalling you can use the @JsonTest annotation. @JsonTest will auto-configure Jackson ObjectMappers and @JsonComponent beans

@RunWith(SpringRunner.class)
@JsonTest
public class ChuckNorrisFactJsonTests {

    private JacksonTester json;

    @Test
    public void serialize() throws IOException {
        ChuckNorrisFact fact = new ChuckNorrisFact("When Chuck Norris turned 18, his parents moved out.");
        JsonContent write = this.json.write(fact);

        assertThat(this.json.write(fact)).isEqualToJson("expected.json");
    }

    @Test
    public void deserialize() throws IOException {
        String content = "{"fact":"Chuck Norris knows Victoria's secret."}";

        assertThat(this.json.parse(content)).isEqualTo(new ChuckNorrisFact("Chuck Norris knows Victoria's secret."));
    }
}

@DataJpaTest

To test the JPA layer of an application you can use @DataJpaTest. By default it configures an in-memory database, scans for @Entity classes and configures the Spring Data JPA repositories. @Service, @Controller, @RestController beans will not be loaded.

@RunWith(SpringRunner.class)
@DataJpaTest
public class ChuckNorrisFactRepositoryTests {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private ChuckNorrisFactRepository repository;

    @Test
    public void getOneRandomly() {
        String fact = "If at first you don't succeed, you're not Chuck Norris.";
        entityManager.persist(new ChuckNorrisFact(fact));

        List<ChuckNorrisFact> facts = repository.getOneRandomly(new PageRequest(0, 10));
        assertThat(facts.get(0).getText(), is(fact));
    }
}

Datasource binding

In Spring Boot 1.4 via spring.datasource property namespace only the common datasource properties are set. For datasource provider specific ones new namespaces were introduced.

spring.datasource.hikari.maximum-pool-size=5
spring.datasource.hikari.connection-timeout=10


Image Banners
You can use an image to render the ASCII banner.

Summary
If you want to try out these new features and enhancements have a look to this github repository.

Spring Boot Related Topics

  1. Spring Boot Interview Questions and Answers
  2. Introduction to Spring Boot
  3. Essentials and Key Components of Spring Boot
  4. Spring Boot CLI Installation and Hello World Example
  5. Spring Boot Initializr Web Interface
  6. Spring Boot Initializr With IDEs
  7. Spring Boot Initializr With Spring Boot CLI
  8. Installing Spring Boot
  9. Developing your first Spring Boot application
  10. External Configurations for Spring Boot Applications
  11. Logging Configuration in Spring Boot
  12. Spring Boot and Spring MVC
  13. Working with SQL Databases and Spring Boot
  14. MySQL Configurations
  15. Spring Data JPA using Spring Boot Application
  16. Spring Boot with NoSQL technologies
  17. Spring Cache Tutorial
  18. Spring Security Tutorial with Spring Boot
  19. Spring Boot and MongoDB in REST Application
  20. Complete Guide for Spring Boot Actuator
  21. Microservices with Spring Boot

How to configure maven in eclipse

In the last tutorial , we have learnt to install maven in our window system. In this tutorial we will learn how to configure our IDE for maven.
In order to use maven with eclipse you must have maven installed on your operating system. 
Follow below steps to configure your Eclipse.
Step 1: Open your eclipse and navigate to help tab and then navigate to eclipse marketplace.
Step 2: Once you reach the eclipse marketplace a pop-up will open and in search option search for 
            “maven”, like indicated in below diagram.
Step 3: You will get many options , but choose for options indicated in the diagram and click on install button.
Step 4 : If everything will be fine it will do some processing and will ask to restart the eclipse. 
How to configure maven in eclipse
Step 5: Verify the installation of maven in eclipse, to verify the installation navigate as stated in pic.
Maven Eclipse configuration
How to configure maven in eclipse IDE
After clicking on the other option, a pop up will pop  with search option. 
In Search option write maven you will get some option related with maven.
If you do not get options related with maven then you need to check the installation again.
To re-verify first check the installation of maven on windows operating system
If you can find maven option (as stated in pics)in eclipse means your IDE is configured with the maven.
In next tutorial we will learn to create new project in eclipse using maven and some deep insight about maven.