Introduction to Spring Boot

This tutorial is adapted from Web Age course Mastering Microservices with Spring Boot and Spring Cloud.

1.  What is Spring Boot?

Spring Boot (http://projects.spring.io/spring-boot/) is a project within the Spring IO Platform (https://spring.io/platform). It was developed in response to Spring Platform Request SPR-9888 "Improved support for 'containerless' web application architectures". It was inspired by the DropWizard Java framework (http://www.dropwizard.io/) . The main focus of Spring Boot is on facilitating a fast-path creation of stand-alone web applications packaged as executable JAR files with minimum configuration. It is an excellent choice for creating microservices. It was released for general availability in April 2014.

Notes:

A JAR (Java ARchive) is a file format and deployment unit used to package a set of Java class files and associated metadata and resources.

2.   Spring Framework

The Spring framework provides comprehensive support for developing Java applications. It lets you utilize features like Dependency Injection and comes with out of the box modules like; Spring JDBC, Spring MVC,  Spring Security, Spring AOP, Spring ORM, Spring Test. These modules can drastically reduce the development time of an application.

3.  How is Spring Boot Related to Spring Framework?

Unlike Spring, Spring Boot is not a framework. Instead, it’s an extension of Spring Framework. It is a way to easily create stand-alone applications with minimal or zero configurations. It provides boilerplate code and annotation configuration to quick start new spring projects. It provides a set of starter pom or gradle build files which one can use to add required dependencies and also facilitate auto configuration. It provides ‘starter’ dependencies to simplify build and application configuration. It provides Embedded HTTP servers like Tomcat, Jetty, etc. to develop and test our web applications very easily. Spring Boot provides lots of plugins to develop and test Spring Boot applications very easily using build tools like Maven and Gradle

4.  Spring Boot Main Features

Spring Boot offers web developers the ability to create WAR-less stand-alone web applications that you can run from command line, embedded web container that is bootstrapped from the public static void main method of your web application module.Tomcat container is default; you have options to plug in Jetty or Undertow containers instead. Minimum, configuration is required to develop applications as Spring Boot relies on Spring MVC annotations (more on annotations later ...) for configuration. It also offers Build-in production-ready features for run-time metrics collection, health checks, and externalized configuration

Notes:

A WAR (Web application ARchive) file is a format for and unit of packaging and distribution of Java- based web applications that are deployed in the web container of a Java-enabled web server.

For steps how to switch from Tomcat to Jetty or Undertow, visit http://docs.spring.io/spring- boot/docs/current/reference/html/howto-embedded-servlet-containers.html

For an overview of the Spring framework, visit http://docs.spring.io/spring/docs/current/spring- framework-reference/html/overview.html

The following diagram, borrowed from the above Spring framework link, lays out the components of a full-fledged Spring web application:

 

5.  Spring Boot on the PaaS

PaaS (Platform as a Service) clouds offer robust, scalable, and cost- efficient run-time environments that can be used with minimum operational involvement. There are two popular choices for deploying Spring Boot applications, Cloud Foundry (https://www.cloudfoundry.org/) and Heroku (https://www.heroku.com/)    Please note that Google App Engine PaaS  has not advanced beyond the Servlet 2.5 API, so you won't be able to deploy a Spring Application there without some modifications. Spring Boot uses Servlet API version 3.1. Spring Boot is being financed by Pivotal Software Inc. which also, in partnership with VMware, sponsor Cloud Foundry. While Cloud Foundry is OSS available for free, Pivotal offers a commercial version of it called Pivotal Cloud Foundry

6.  Understanding Java Annotations

Annotations in Java are syntactic metadata that is baked right into Java source code; you can annotate Java classes, methods, variables and parameters. Basically, an annotation is a kind of label that is processed during a compilation stage by annotation processors when the code or configuration associated with the annotation is injected in the resulting Java class file, or some additional operations associated with the annotation are performed. An annotation name is prefixed with an '@' character.

Note: Should you require to change annotation-based configuration in your application, you would need to do it at source level and then re-build your application from scratch

7.  Spring MVC Annotations

Spring Boot leverages Spring MVC (Model/View/Controller) annotations instead of XML-based configuration. Additional REST annotations, like @RestController have been added with Spring 4.0

The main Spring MVC annotations are,  @Controller / @RestController, @RequestMapping and  @RequestParam . @Controller / @RestController annotate a Java class as an HTTP end-point. @RequestMapping – annotate a method to configure with URL path / HTTP verb the method responds to. @RequestParam - named request parameter extracted from client HTTP request.

8.  Example of Spring MVC-based RESTful Web Service

The following code snippet shows some of the more important artifacts of Spring MVC annotations (with REST-related Spring 4.0 extensions) that you can apply to your Java class.

Note: Additional steps to provision and configure a web container to run this module on are required

// … required imports are omitted @RestController

public class EchoController { @RequestMapping("/echoservice", method=GET)

public String echoback(@RequestParam(value="id") String echo) { return echo;

}

}

The above annotated Java class, when deployed as a Spring MVC module, will echo back any echo message send with an HTTP GET request to this URL:

http(s)://<Deployment-specific>/echoservice?id=hey

9.  Spring Booting Your RESTful Web Service

Spring Boot allows you to build production-grade web application without the hassle of provisioning, setting up, and configuring the web container. A Spring Boot application is a regular executable JAR file that includes the required infrastructure components and your compiled class that must have the public static void main method which is called by the Java VM on application submission. The public static void main method references the SpringApplication.run method that loads and activates Spring annotation processors, provisions the default Tomcat servlet container and deploys the Spring Boot-annotated modules on it.

10.  Spring Boot Skeletal Application Example

The following code is a complete Spring Boot application based on the Spring MVC REST controller :

// … required imports are omitted

@SpringBootApplication @RestController

public class EchoController { @RequestMapping("/echoservice", method=GET)

public String echoback(@RequestParam(value="id") String echo) {

return echo;

}

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

}

}

You run Spring Boot applications from command line as a regular executable JAR file:

java -jar Your_Spring_Boot_App.jar

 The default port the Spring Boot embedded web container starts listening to is 8080

 To change the default port, you need to pass a server.port System property or specify it in the Spring's application.properties file

Notes:

The @SpringBootApplication is functionally equivalent to three annotations applied sequentially:

@Configuration, @EnableAutoConfiguration, and @ComponentScan

11.  Converting a Spring Boot Application to a WAR File

In some scenarios, users want to have a Sprint Boot runnable JAR file converted into a WAR file. 

For those situations, Spring Boot provides two plug-ins:

◊    spring-boot-gradle-plugin for the Gradle build system (https://gradle.org/)

◊    spring-boot-maven-plugin for the Maven build system (https://maven.apache.org/)

For more details on Spring Boot JAR to WAR conversion, visit

https://spring.io/guides/gs/convert-jar-to-war/

12.  Externalized Configuration

Externalized Configuration lets you deploy the same Spring Boot artifact (jar file) in different environments - config is drawn from the environment. Properties are pulled from OS Environment variable SPRING_APPLICATION_JSON,  Java System properties, OS Environment variables and     Application property files - application.properties or application.yml. Spring Application load properties from application.properties file in the '/config' folder in current directory, in the current directory, in a classpath '/config' package, in the classpath root and in a folder pointed to by 'spring.config.location' on the command line.

13.  Starters

Spring Boot auto-configures based on what it finds in the classpath. So, the set of modules is determined by what's in the 'pom.xml'. The project provides a number of 'starter' artifacts that pull in the correct dependencies for a given technology.Some examples are spring-boot-starter-web, spring-boot-starter-jdbc and  spring-boot-starter-amqp.You just need to include these artifacts in the 'pom.xml' to configure those technologies.

14.  Maven - The 'pom.xml' File

Assuming you're building with Apache Maven, the 'pom.xml' file describes all the artifacts and build tools that go into producing a delivered artifact. Generally, use the 'starter parent':

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.4.2.RELEASE</version>

</parent>

It defines all the dependency management and core dependencies for a Spring Boot application

15.  Spring Boot Maven Plugin

The Maven plugin can package the project as an executable jar file, that includes all the dependencies.

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven- plugin</artifactId>

</plugin>

</plugins>

</build>

16.  Gradle - The 'build.gradle' File

To define the dependencies, use the dependencies block as shown below:

dependencies {

implementation 'org.springframework.boot:spring-boot- dependencies:2.0.5.RELEASE'

implementation 'org.springframework.boot:spring-boot-starter-web'

testImplementation 'org.springframework.boot:spring- boot-starter-test'

}

It defines the dependency management and core dependencies for a Spring Boot application

17.  Spring Boot Maven Plugin

Spring provides a standalone Spring Boot Gradle plugin which adds some tasks and configurations to ease the work with Spring Boot based projects. Assuming you're building with Gradle, the 'build.gradle' file describes all the artifacts and build tools that go into producing a delivered artifact.

plugins {

id 'java'

id 'com.gradle.build-scan' version '2.0.2'

id 'org.springframework.boot' version '2.0.5.RELEASE'

id 'io.spring.dependency-management' version '1.0.7.RELEASE'

}

18.  How to Create a Spring Boot Application?

  • Create a new Maven project in the IDE of your choice
  • In 'pom.xml',
    • add the Spring Boot parent project (see above)
    • Add dependencies to the 'starter' projects that describe the features you want (e.g. Spring MVC, JDBC, etc)
    • Add the 'spring-boot-maven-plugin' to the build plugins
  • Add a default 'application.properties' or 'application.yml' file in 'src/main/resources'
  • Create a main class in src/main/java/<package>
  • e.g. in 'com.mycom.app',

@SpringBootApplication public class MyApp {

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

}}

  • Build with 'mvn install'
  • From the IDE, run the main class
  • From command line, run the jar file

20.  Summary

Spring Boot eliminates many of the headaches related to provisioning, setting up and configuring a web server by offering a framework for running WAR-less web applications using embedded web containers

Spring Boot favors annotation-based configuration over XML-based one.Any change to such a configuration (e.g. a change to the path a REST- enabled method responds to), would require changes at source level and recompilation of the project. Spring Boot leverages much of the work done in Spring MVC

Karandeep Kaur August 27, 2019

Leave a Reply

Your email address will not be published. Required fields are marked *

Web age solutions blog Zones