Saturday, March 10, 2018

Create your first Spring Boot web application with Maven & Thymeleaf: 4 Steps(with Screenshots)

Hello Friends!! If you have ever developed the enterprise spring-based applications then you would surely know the pain for making bulky configuration along with the complicated dependency management. Today we would see how Spring Boot takes this pain away. To demonstrate this, we would discuss step by step process to create our first Spring Boot web application using Spring Tool Suite(STS) and then explain how this has become possible using Spring Boot. Don't worry if haven't developed any spring-based application before because this would be very easy to follow guide.
Table Of Content
1. Introduction
2. Scope
3. Tools & Technology Stack Used
4. Steps to create web application
5. Why Spring Boot?
6. Conclusion


1. Introduction


Spring Boot is an application framework that not only accelerate the development but also helps in setting up an enterprise Spring-based application easily. It follows software design paradigm like Convention over Configuration & Rapid Application Development which means it provides sensible defaults to its user, obviously by following the best practices and without losing flexibility. Therefore it makes it easy to create applications. We would understand this by an example.

2. Scope 


We would be describing step by step approach for developing our first web application using Spring Boot & Thymeleaf. It will be a Maven based project. Taking this application as reference, we would also discuss below points:
  • How does Spring Boot facilitated development at faster pace?
  • How does Spring Boot simplified the complex dependency management compatibility issues?
  • How does Spring Boot simplified the deployment process?

3. Tools & Technology Stack Used


- Spring Tool Suite: 3.9.0.RELEASE
- Spring Boot: 1.5.10.RELEASE
- Spring: 4.3.14.RELEASE
- Thymeleaf: 2.1.6.RELEASE
- Tomcat Embed: 8.5.27
- Maven: 3.3.9
- Java: 1.8.0_144

4. Steps to create web application 


Open the Spring Tool Suite (STS) and follow the below steps to create the web application using Spring Boot:

Step 1: From STS IDE, go to File > New > Spring Starter Project to launch the "New Spring Starter Project" window


In the New Spring Starter Project window, fill up the required details like Name, Group Id, Artifact Id, Description, Package and then Click on Next. A New Spring Starter Project Dependencies window would open.


Note: Have you noticed the Service URL field value [http://start.spring.io]. See [1].

Step 2: Choose the required Spring Boot version and project dependencies from New Spring Starter Project Dependencies window and then Click on Next.

Note: Selecting project dependencies is optional at this stage. One could always add project dependecies directly to their project's pom.xml.

After clicking on Next button, in the resulting window, one needs to click on Finish.


Default project hierarchy of our Spring Boot application will be created along with the police.xml file. The only remaining job is to add our controller & html files.

Step 3: Add the Controller class & resource files like HTML, CSS & JS

Let's see the project hierarchy after adding the required controller class & resource files.

Package Explorer View in STS:

Note: Wondering what is [devtools], see [2]

Navigator View in STS:


Here, we have only created the below items. We haven't changed anything in anyplace i.e. nothing changed in generated Java file or pom.xml.
- Package com.anshulsblog.service.web.controller inside src/main/javaMainController.java
package com.anshulsblog.service.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {
 
 private String message = "Hello Friends!! Welcome to the world of Spring Boot.";
 
 @RequestMapping("/")
 public String welcome(ModelMap model) {
  model.addAttribute("message", this.message);
  return "welcome";
 }
}

- Folder css inside src/main/resources/static/screen.css
.header-container {
    background-color: #3e484f;
    height: 6em; 
    width: 100%; 
    position: fixed;
    top: 0;
}
.horizontal-nav {
    margin-left: 775px;
    padding-top: 21px;
}
.horizontal-nav > ul > li {
    list-style-type: none;
    display: inline;
    line-height: 24px;
}
.horizontal-nav > ul > li > a {
    padding: 8px 20px;
    text-decoration: none;
    float: none;
    color: #8c9ca8;
    font-size: 20px;
}
.logo {
    color: #8c9ca8;
    margin-left: 30px;
    margin-top: 30px;
    font-size: 30px;
    float: left;
}
.main-body {
  margin-top:40px;
  background-color: white;
  padding: 99px;
  width: 100%; 
  text-align: left;
   
}
.page-section-content {
    border-radius: 5px;
    font-size: 17px;
    text-align: justify;
    font-family: "Open Sans",sans-serif;
    margin-right: 300px;
}
#welcome {
    color: red;
}
- HTML file i.e. welcome.html inside src/main/resources/templates
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
 <title>Spring Boot Example with Maven and Thymeleaf</title>
 <link rel="stylesheet" type="text/css" th:href="@{/css/screen.css}" href="/css/screen.css" />
</head>
<body>
 <div class="header-container">
 <div class="header">
  <div class="logo">
  Spring Boot
  </div>
  <nav class="horizontal-nav">
    <ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="About-Us.html">About Us</a></li>
    <li><a href="contact-us.html">Contact Us</a></li>
   </ul>
  </nav>
 </div>
</div>
<div class="main-body">
 <span id="welcome" th:text="${message}"></span>
 <div class="page-header">
  <h2>Building a Web Application Using Spring Boot</h2>
 </div>
 <div class="page-section-content">
  This article would provide a step by step guide to build a Maven based web application using Spring Boot. We would see how easily one could create stand-alone application in no time. 
  We will be using below tools and technologies to build our sample application:
  <ul>
   <li>Spring Tool Suite : 3.9.0.RELEASE</li>
   <li>Spring Boot: 1.5.10.RELEASE</li>
   <li>Spring: 4.3.14.RELEASE</li>
   <li>Thymeleaf: 2.1.6.RELEASE</li>
   <li>Tomcat Embed: 8.5.27</li>
   <li>Maven: 3.3.9</li>
   <li>Java: 1.8.0_144</li>
  </ul>
 </div>
</div>
</body> 
</html>
 - Optional: If one wants to run the application in different port [other then 8080 ] then configure the embedded Tomcat port in /src/main/resources/application.properties
server.port = 8090
Step 4: Run Spring Boot application: Select the project, Right Click and, move to Run As and click on Spring Boot App
17:59:43.237 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
17:59:43.239 [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/]
17:59:43.239 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/D:/Workspaces/anshulsblog/web-application/target/classes/]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

2018-03-01 17:59:44.061  INFO 25060 --- [  restartedMain] c.a.service.web.WebApplication           : Starting WebApplication on 01HW561442 with PID 25060 (D:\Workspaces\anshulsblog\web-application\target\classes started by 559355 in D:\Workspaces\anshulsblog\web-application)
2018-03-01 17:59:44.062  INFO 25060 --- [  restartedMain] c.a.service.web.WebApplication           : No active profile set, falling back to default profiles: default
2018-03-01 17:59:44.457  INFO 25060 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@a7c83b5: startup date [Thu Mar 01 17:59:44 IST 2018]; root of context hierarchy
2018-03-01 17:59:46.217  INFO 25060 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8090 (http)
2018-03-01 17:59:46.228  INFO 25060 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-03-01 17:59:46.229  INFO 25060 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-03-01 17:59:46.325  INFO 25060 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-03-01 17:59:46.326  INFO 25060 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1872 ms
2018-03-01 17:59:46.535  INFO 25060 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-03-01 17:59:46.538  INFO 25060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-01 17:59:46.538  INFO 25060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-01 17:59:46.538  INFO 25060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-01 17:59:46.538  INFO 25060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-03-01 17:59:46.916  INFO 25060 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@a7c83b5: startup date [Thu Mar 01 17:59:44 IST 2018]; root of context hierarchy
2018-03-01 17:59:46.978  INFO 25060 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.anshulsblog.service.web.controller.MainController.welcome(org.springframework.ui.ModelMap)
2018-03-01 17:59:46.981  INFO 25060 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-01 17:59:46.981  INFO 25060 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-01 17:59:47.013  INFO 25060 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-01 17:59:47.013  INFO 25060 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-01 17:59:47.041  INFO 25060 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-01 17:59:47.531  INFO 25060 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2018-03-01 17:59:47.585  INFO 25060 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-03-01 17:59:47.666  INFO 25060 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8090 (http)
2018-03-01 17:59:47.669  INFO 25060 --- [  restartedMain] c.a.service.web.WebApplication           : Started WebApplication in 4.407 seconds (JVM running for 5.907)

Access the application: http://localhost:8090/


What just happened?
We have just specified the Maven coordinate and required project dependencies through STS. It has created the boilerplate project folder structure along with our main Java class and pom.xml. We have then added our controller and resource files. That's it, we are done. Ran the application, saw the output.

5. Why Spring Boot?


Before starting, be clear on few points:
  • Have we configured DispatcherServlet, HandlerMappings, ViewResolvers anywhere?
  • Have we explicitly defined or configured spring-webmvc, spring-web, spring-context, spring-beans, spring-aop, jackson-databind, hibernate-validator modules anywhere as these are generally needed for a web application? Forget about the compatible version of these libraries.
  • Have we generated our application's war, configured any Servlet container and then deployed the WAR in it explicitly? 
The answer of above questions would be NO, we haven't defined or configured above modules anywhere and haven't configured any Servlet container like Tomcat either.

Then how our application is up & running? 

The answer to this question is hidden in our application's pom.xml & main application class that is automatically generated by STS . Let's go through it...
<?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.anshulsblog</groupId>
 <artifactId>web-application</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>web-application</name>
 <description>Spring Boot Project: Using embedded Tomcat + Thymeleaf template engine</description>

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

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

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</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>
  
  <!-- Optional, disables the caching options by default, Automatic Restart of the Application:  -->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <optional>true</optional>
  </dependency>
  
 </dependencies>

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


</project>

As told earlier, Spring Boot follows software design paradigm like Convention over Configuration. It will take an opinionated view of the Spring platform and third-party libraries. Therefore it would provide sensible defaults for their users [by convention] and if one deviates/departs from the these defaults then only one needs to make any configuration changes.

Divide POM & Understand:
  • Line 4: Maven 2.x / 3.x use a <modelVersion>4.0.0</modelVersion> element. It simply means that our POM is compatible with Maven 3. 
  • Line 6 to 8: Defined the Maven Coordinate of our application
  • Line 9: Artifact Packaging type i.e. JAR or WAR. By default it would be JAR. 
  • Line 14 to 19: Place where Spring Boot version is defined. Our application obtain sensible defaults using spring-boot-starter-parent like Sensible resource filtering, Sensible plugin configuration, A Dependency Management section [manages the versions of common dependencies, therefore one need not to provide <version> tags for those dependencies] etc. For more details, read this - spring-boot-starter-parent
  • Line 28 to 35: Added the starters like spring-boot-starter-web & spring-boot-starter-thymeleaf. This is where all the real work is done.

    Note: Starters are a set of convenient dependency descriptors that provides one-stop shop for all the Spring and related technologies that one will need. One need not to hunt through sample code and copy-paste loads of dependency descriptors because the starters contain a lot of the dependencies that a developer will need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies. For example:  wants to get started with Spring & JPA for database access, including the spring-boot-starter-data-jpa dependency in the project will do the job.

    Gone are the days of the traditional application development using Spring framework, when one had to perform below tasks in order to develop particular type of application:
      - Finding out the required spring modules like Spring MVC, Spring JDBC, Spring ORM etc
      - Finding out the required common 3rd party libraries
      - Haunt for compatible version of libraries with one another
      - Multiple configurations depending upon the application type like DispatcherServlet,       HandlerMappings, ViewResolvers , DAO etc

    We are developing the web application and we have used spring-boot-starter-web, spring-boot-starter-thymeleaf  spring-boot-starter-test. Let's discuss the utility of these starters :

    spring-boot-starter-web: Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
    spring-boot-starter-thymeleaf: Starter for building MVC web applications using Thymeleaf views
    spring-boot-starter-test: Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito

    Would like to know more about Starters & available starters at our disposal then read this - Spring Boot Starters

    Let's see the dependency tree of our application then one will get to know that all the required jars all automatically include.
    [INFO] Scanning for projects...
    [INFO]                                                                         
    [INFO] ------------------------------------------------------------------------
    [INFO] Building web-application 0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO] 
    [INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ web-application ---
    [INFO] com.anshulsblog:web-application:jar:0.0.1-SNAPSHOT
    [INFO] +- org.springframework.boot:spring-boot-starter-thymeleaf:jar:1.5.10.RELEASE:compile
    [INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.5.10.RELEASE:compile
    [INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.5.10.RELEASE:compile
    [INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.1.11:compile
    [INFO] |  |  |  |  \- ch.qos.logback:logback-core:jar:1.1.11:compile
    [INFO] |  |  |  +- org.slf4j:jcl-over-slf4j:jar:1.7.25:compile
    [INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.25:compile
    [INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.25:compile
    [INFO] |  |  \- org.yaml:snakeyaml:jar:1.17:runtime
    [INFO] |  +- org.thymeleaf:thymeleaf-spring4:jar:2.1.6.RELEASE:compile
    [INFO] |  |  +- org.thymeleaf:thymeleaf:jar:2.1.6.RELEASE:compile
    [INFO] |  |  |  +- ognl:ognl:jar:3.0.8:compile
    [INFO] |  |  |  +- org.javassist:javassist:jar:3.21.0-GA:compile
    [INFO] |  |  |  \- org.unbescape:unbescape:jar:1.1.0.RELEASE:compile
    [INFO] |  |  \- org.slf4j:slf4j-api:jar:1.7.25:compile
    [INFO] |  \- nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:jar:1.4.0:compile
    [INFO] |     \- org.codehaus.groovy:groovy:jar:2.4.13:compile
    [INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.5.10.RELEASE:compile
    [INFO] |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:1.5.10.RELEASE:compile
    [INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:8.5.27:compile
    [INFO] |  |  |  \- org.apache.tomcat:tomcat-annotations-api:jar:8.5.27:compile
    [INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:8.5.27:compile
    [INFO] |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.5.27:compile
    [INFO] |  +- org.hibernate:hibernate-validator:jar:5.3.6.Final:compile
    [INFO] |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
    [INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.3.1.Final:compile
    [INFO] |  |  \- com.fasterxml:classmate:jar:1.3.4:compile
    [INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.10:compile
    [INFO] |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.0:compile
    [INFO] |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.8.10:compile
    [INFO] |  +- org.springframework:spring-web:jar:4.3.14.RELEASE:compile
    [INFO] |  |  +- org.springframework:spring-aop:jar:4.3.14.RELEASE:compile
    [INFO] |  |  +- org.springframework:spring-beans:jar:4.3.14.RELEASE:compile
    [INFO] |  |  \- org.springframework:spring-context:jar:4.3.14.RELEASE:compile
    [INFO] |  \- org.springframework:spring-webmvc:jar:4.3.14.RELEASE:compile
    [INFO] |     \- org.springframework:spring-expression:jar:4.3.14.RELEASE:compile
    [INFO] +- org.springframework.boot:spring-boot-starter-test:jar:1.5.10.RELEASE:test
    [INFO] |  +- org.springframework.boot:spring-boot-test:jar:1.5.10.RELEASE:test
    [INFO] |  +- org.springframework.boot:spring-boot-test-autoconfigure:jar:1.5.10.RELEASE:test
    [INFO] |  +- com.jayway.jsonpath:json-path:jar:2.2.0:test
    [INFO] |  |  \- net.minidev:json-smart:jar:2.2.1:test
    [INFO] |  |     \- net.minidev:accessors-smart:jar:1.1:test
    [INFO] |  |        \- org.ow2.asm:asm:jar:5.0.3:test
    [INFO] |  +- junit:junit:jar:4.12:test
    [INFO] |  +- org.assertj:assertj-core:jar:2.6.0:test
    [INFO] |  +- org.mockito:mockito-core:jar:1.10.19:test
    [INFO] |  |  \- org.objenesis:objenesis:jar:2.1:test
    [INFO] |  +- org.hamcrest:hamcrest-core:jar:1.3:test
    [INFO] |  +- org.hamcrest:hamcrest-library:jar:1.3:test
    [INFO] |  +- org.skyscreamer:jsonassert:jar:1.4.0:test
    [INFO] |  |  \- com.vaadin.external.google:android-json:jar:0.0.20131108.vaadin1:test
    [INFO] |  +- org.springframework:spring-core:jar:4.3.14.RELEASE:compile
    [INFO] |  \- org.springframework:spring-test:jar:4.3.14.RELEASE:test
    [INFO] \- org.springframework.boot:spring-boot-devtools:jar:1.5.10.RELEASE:compile
    [INFO]    +- org.springframework.boot:spring-boot:jar:1.5.10.RELEASE:compile
    [INFO]    \- org.springframework.boot:spring-boot-autoconfigure:jar:1.5.10.RELEASE:compile
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 5.053 s
    [INFO] Finished at: 2018-03-07T18:08:01+05:30
    [INFO] Final Memory: 22M/307M
    [INFO] ------------------------------------------------------------------------
  • Line 44 to 48: Added spring-boot-devtools (Optional) dependencies manually to accelerate and enjoy the application development experience as it provides additional development-time features. See [2]
  • Line 54 to 57: Automatically added spring-boot-maven-plugin.
    - It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport our service.
    - It searches for the public static void main() method to flag as a runnable class.

Let's also discuss our main application i.e. class having @SpringBootApplication annotation
/web-application/src/main/java/com/anshulsblog/service/web/WebApplication.java
package com.anshulsblog.service.web;

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

@SpringBootApplication
public class WebApplication {

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

The main showstopper here is @SpringBootApplication annotation. Due to this annotations, we got the auto-configuration feature. @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes. 
  • @Configuration: It tags the class as a source of bean definitions for the application context. It means, one can define beans here using Java configuration. 
  • @EnableAutoConfiguration: It tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. How cool is this feature?
    - Notices spring-mvc.jar  on the classptah then automatically configure DispatcherServlet
    - Sees the spring-webmvc on the classpath then automatically add @EnableWebMvc
  • @ComponentScan: It tells Spring to look for other components, configurations, and services in the base package [or specified path].
The main() method uses Spring Boot’s SpringApplication.run() method to launch the application. Notice that, there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and one didn’t have to deal with configuring any plumbing or infrastructure.

6. Conclusion 


Spring Boot has simplified the application development by providing awesome Auto-configuration feature, various types of Starters for different use cases, dev-tools, embedded container for easier deployment and many more. It takes the "opinionated" approach to configuration and provides intelligent defaults without loosing flexibility. Therefore enjoy the pleasant application development experience using Spring Boot. Happy Learning!!


Appendix 


[1] : http://start.spring.io
Open this URL in the browser, one would see something like


One can use this to create Spring Boot application just like we are doing using STS. Fill up the required details and click on Generate Project. A zip file with the name of the artifact will be downloaded in your system. Import it into the IDE of your choice and enjoy coding.

[2] : spring-boot-devtools :It provides additional development-time features like
Disables the caching options by default: As caching is counter-productive during development, preventing us from seeing the changes we just made in our application.
Automatic Restart of the Application: Amplify the feedback loop for code changes. Don't need to stop & restart the application every time after making code changes.
Live Reload: By default changing resources in /META-INF/maven, /META-INF/resources, /resources, /static, /public or /templates will not trigger a restart but will trigger a live reload.

No comments:

Post a Comment