Introduction to Spring Boot

0

Spring Boot eases creating spring based application. One doesn’t need to depend on XML for configuration. It uses annotations for auto configuration and one can come up with a running application very fast. The first draft of the application, auto-created by the spring boot is opinionated. This is obvious as its main goal is to developĀ application at a very speedy manner, having said that, one can easily extend it and get out of itsĀ initial framework.

It allows one to add Spring Boot Starters and dependencies to your application and then generate the project. See spring starter site to build one by yourself.

Creating spring boot Web MVC project using spring starter

The ideal way would be to go to http://start.spring.io/, click on ‘Switch to Full Version’ and select ‘Web’ as dependency.

Using spring starter

Using spring starter

Enter groupID and artifactID. Click on ‘Generate Project’ to download the project. Extract the downloaded zip file. Import the project as an ‘Existing Maven Project’.

Dependencies

For building the project, we can use either Maven or Gradle. In the spring starter page, by default, Maven is selected.

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.javarticles.springboot</groupId>
	<artifactId>springBootWebMvc</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

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

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.1.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-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>

Few points to note about in the above pom.xml:

  1. We inherit spring provided artifact spring-boot-starter-parent to make use of the Maven defaults.
  2. Based on the needs of our application, we will add other dependencies. For example, since we are developing web application, we have added spring-bootstarter-web dependency
  3. To create an executable jar we need to add the spring-boot-maven-plugin to our pom.xml.
  4. Java version is set to 1.8
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<java.version>1.8</java.version>
    	</properties>
    

Spring Boot is dependent on third party libraries and the spring framework itself. The dependencies are managed by spring boot itself and we should avoid override the versions of these libraries.

Spring Boot Main Class

SpringBootWebMvcApplication is the main class. This is an auto-generated class. In the main method, SpringApplication.run() is called which in turn delegates the control to spring boot’s SpringApplication. Once spring boot takes charge, SpringApplication will bootstrap our application. Spring will in turn start the embedded auto-configured Tomcat web server.
SpringBootWebMvcApplication is passed in as the first argument to SpringApplication.run().

SpringBootWebMvcApplication:

package com.javarticles.springboot;

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

@SpringBootApplication
public class SpringBootWebMvcApplication {

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

Add RequestMapping

We will modify the main class to add in a request mapping.
We have done couple of changes here:

  1. Annotated the main class with @RestController – this is to mark the class as a web controller and let Spring know that the class is going to handle incoming web requests.
  2. Add a request handler – Method sayHello() is marked with @RequestMapping("/sayHello") annotation. When the relative path is “/sayHello”, this method will handle the request.

SpringBootWebMvcApplication:

package com.javarticles.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class SpringBootWebMvcApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootWebMvcApplication.class, args);
	}
	
	@RequestMapping("/sayHello")
	public String sayHello() {
	    return "Hello";
	}
}

Few observations from the output:

  1. Starts embedded tomcat, listening on 8080.
  2. WebApplicationContext is loaded.
  3. Request mapping /sayHello is mapped to SpringBootWebMvcApplication.sayHello().

Output:

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

2016-01-07 07:46:04.467  INFO 18328 --- [           main] c.j.s.SpringBootWebMvcApplication        : Starting SpringBootWebMvcApplication on INMAA1-L1005 with PID 18328 (C:\javarticles_ws\springBootWebMvc\target\classes started by mokkara in C:\javarticles_ws\springBootWebMvc)
2016-01-07 07:46:04.470  INFO 18328 --- [           main] c.j.s.SpringBootWebMvcApplication        : No active profile set, falling back to default profiles: default
2016-01-07 07:46:04.515  INFO 18328 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]710726a3: startup date [Thu Jan 07 07:46:04 IST 2016]; root of context hierarchy
2016-01-07 07:46:05.031  INFO 18328 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-01-07 07:46:05.764  INFO 18328 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-01-07 07:46:05.785  INFO 18328 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-01-07 07:46:05.787  INFO 18328 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.30
2016-01-07 07:46:05.886  INFO 18328 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-01-07 07:46:05.886  INFO 18328 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1374 ms
2016-01-07 07:46:06.134  INFO 18328 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2016-01-07 07:46:06.137  INFO 18328 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-01-07 07:46:06.137  INFO 18328 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-01-07 07:46:06.138  INFO 18328 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-01-07 07:46:06.138  INFO 18328 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2016-01-07 07:46:06.347  INFO 18328 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]710726a3: startup date [Thu Jan 07 07:46:04 IST 2016]; root of context hierarchy
2016-01-07 07:46:06.415  INFO 18328 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/sayHello]}" onto public java.lang.String com.javarticles.springboot.SpringBootWebMvcApplication.sayHello()
2016-01-07 07:46:06.418  INFO 18328 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-01-07 07:46:06.419  INFO 18328 --- [           main] 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)
2016-01-07 07:46:06.442  INFO 18328 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-01-07 07:46:06.442  INFO 18328 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-01-07 07:46:06.480  INFO 18328 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-01-07 07:46:06.592  INFO 18328 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-01-07 07:46:06.659  INFO 18328 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-01-07 07:46:06.662  INFO 18328 --- [           main] c.j.s.SpringBootWebMvcApplication        : Started SpringBootWebMvcApplication in 2.447 seconds (JVM running for 2.71)
2016-01-07 07:46:21.658  INFO 18328 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-01-07 07:46:21.658  INFO 18328 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-01-07 07:46:21.669  INFO 18328 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 11 ms

Test the spring boot application

Enter http://localhost:8080/sayHello in browser.

Output:

Hello

Download the source code

This was an example to introduce spring boot.

You can download the source code here: springBootWebMvc.zip
Share.

Comments are closed.