Spring Boot Introduction

Today world moves toward Micro Services. Instead of developing large monolithic applications, we are building lots of Micro Services. One of the important things with these Micro Services is you would want to be able to build them quickly. That’s where Spring Boot comes in. Next, let’s first discuss about the goals an the important features of Spring Boot.

1. Goals and important features

Two Goals
The most important goal of Spring Boot is to enable building production ready applictions quickly. Another important goal is to provide all the common non-functional features, e.g. embedded servers, metrics, health checks and externalized configuration.

What Spring Boot is Not !

  • Zero code generation.There is no code generation at all!
  • Neither an application server nor a web server.Spring boot is neither an application server nor a web server. Spring boot provides great integreation with embedded servers like Tomcat, Jetty but by itself Spring Boot is not a web server and it’s not an application server.

Features

  • Quick starter projects with auto configuration
    • Web. For example, if I’m using Spring MVC, I would configure dispatcher servlet. I would need to configure view resolver and a lot of things like that. However, with Spring Boot Starter project it becomes very easy. All that you need to do is to add a starter called Spring starter web into your project and that’s it. You’ll get to Spring MVC for free. You’ll get to Spring core for free. You get a validation framework for free and also a logging framework for free.
    • JPA. Similarly, for JPA there is a starter called Spring Boot starter JPA. Once we use that starter. You would not only get JPA but also a default implementation of JPA with Hibernate and also auto configuration of that.
  • Embedded Servers - Tomcal, Jetty or Undertow. Previously, we would need to install a web server and then I would take my application war and deploy it. This is the ususal way we use to deploy stuff. With Spring Boot, comes a concept called embedded server. What you can do is you can package your server, you can package Tomcat along with your application jar. So I don’t need to install it. In the world of Micro Services, this makes a huge difference.
  • Production-ready features
    • metrics, health checks. Spring boot provides monitoring for your application through something called Spring actuator. For example, you can find out how many times a particular service is called or failed and also you can check whether the application is up and running or not. All these freatures come built in.
    • externalized configuration. The configuration of applications varies between different environments. The configuration from dev different from the configuration in production. Spring boot provides these features built in. You can simply create property files matching a simple naming convention and that’s it.

2. Developing Spring Applications before Spring Boot

To build a Spring MVC project, we need to decide what dependencies to add into our project as well as their comparable version.
We need to implement default exception handling. And we need a complete Spring configuration file. We needed to define the component scan and then we would need to configure a view resolver to redirect the views to JSP.
And in addition to that we needed to configure our web.xml as well. We needed ot configure the dispatcher servlet in web.xml so that it can handle all the requests and act as a front controller. We needed to configure the context configuration location, spring security as well as the filter for it to make sure that it intercepts all the request.
All these stuff we don’t need to do with Spring Boot. Spring Boot would automatically provide all that stuff. These stuff would be replaced by a simple starter project called Spring Boot startup web in combination with Spring Boot starter security.

3. Using Spring Initializer to Create a Spring Boot Application

  • go to start.spring.io and generate a maven project with java and spring boot 2.2.0 SNAPSHot.Give Group Id and Artifact Id. Add dependencies, including Spring Web Starter, JPA, Security, Dev,…
  • import the project in IDE.

4. Creating a Simple RESTful Controller

5. What is Spring Boot Auto COnfiguration?

First, let’s look at file SpringBootDemoAPpplication.java. That is,

package com.example.springbootdemo;

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

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

The annotation @SpringBootApplication does several things.

  • One, it indicates that this is a Spring context file.
  • Two, it enables someting called auto configuration.
  • Three, it enables something called component scan.

Component scan is one of the important features of Spring where it would start automatically scanning the classes in package com.example.springbootdemo. And its sub package for any beans.
Since we have added an annotation @RestController above BooksController. So BooksController would be registered as a bean and it would be managed by the Spring framework.

Next, let’s look at auto configuration in depth. Method SpringApplication.run() is used to run a Spring context. So I’m giving a Spring context as an input to it and it would be able to run that. The run method also return somethong. It returns the application context back. For example,

public static void main(String[] args) {
  ApplicationContext applicationContext = SpringApplication.run(SpringBootDemoApplication.class, args);

  for (String name: applicationContext.getBeanDefinitionNames()) {
    System.out.println(name);
  }
}

The output is:

CLICK
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
springBootDemoApplication
org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
booksController
org.springframework.boot.autoconfigure.AutoConfigurationPackages
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
propertySourcesPlaceholderConfigurer
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$TomcatWebSocketConfiguration
websocketServletWebServerCustomizer
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat
tomcatServletWebServerFactory
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
servletWebServerFactoryCustomizer
tomcatServletWebServerFactoryCustomizer
server-org.springframework.boot.autoconfigure.web.ServerProperties
org.springframework.boot.context.internalConfigurationPropertiesBinder
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
webServerFactoryCustomizerBeanPostProcessor
errorPageRegistrarBeanPostProcessor
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
dispatcherServlet
spring.http-org.springframework.boot.autoconfigure.http.HttpProperties
spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration
dispatcherServletRegistration
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration
taskExecutorBuilder
applicationTaskExecutor
spring.task.execution-org.springframework.boot.autoconfigure.task.TaskExecutionProperties
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration
defaultValidator
methodValidationPostProcessor
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
error
beanNameViewResolver
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration
conventionErrorViewResolver
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
errorAttributes
basicErrorController
errorPageCustomizer
preserveErrorControllerTargetClassPostProcessor
spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
faviconHandlerMapping
faviconRequestHandler
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration
requestMappingHandlerAdapter
requestMappingHandlerMapping
mvcConversionService
mvcValidator
mvcContentNegotiationManager
mvcPathMatcher
mvcUrlPathHelper
viewControllerHandlerMapping
beanNameHandlerMapping
routerFunctionMapping
resourceHandlerMapping
mvcResourceUrlProvider
defaultServletHandlerMapping
handlerFunctionAdapter
mvcUriComponentsContributor
httpRequestHandlerAdapter
simpleControllerHandlerAdapter
handlerExceptionResolver
mvcViewResolver
mvcHandlerMappingIntrospector
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
defaultViewResolver
viewResolver
welcomePageHandlerMapping
requestContextFilter
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
hiddenHttpMethodFilter
formContentFilter
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration
springApplicationAdminRegistrar
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration
standardJacksonObjectMapperBuilderCustomizer
spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
jacksonObjectMapperBuilder
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration
parameterNamesModule
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
jacksonObjectMapper
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
jsonComponentModule
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
stringHttpMessageConverter
org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
mappingJackson2HttpMessageConverter
org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration
messageConverters
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration
spring.security.oauth2.resourceserver-org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration
taskSchedulerBuilder
spring.task.scheduling-org.springframework.boot.autoconfigure.task.TaskSchedulingProperties
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
restTemplateBuilder
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguration
tomcatWebServerFactoryCustomizer
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
characterEncodingFilter
localeCharsetMappingsCustomizer
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
multipartConfigElement
multipartResolver
spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties

We get lots of things printed. So there are a host of things that are getting configured for us automatically.
How are these being configured? That’s basically the feature called auto configuration. What Spring Boot does is as part of the Spring Boot framework, there is something called Spring Boot auto configure. What would happen at startup is the Spring Boot framework would trigger the auto configuration jar. And it would loop through classes which are on the classpath.
For example, it would see that there is a spring-mvc framework on the classpath. Then what does Spring Boot auto configure do ? It would configure a dispatcher servlet and view resolver.

In summurize, Spring Boot looks at a) Frameworks available on the CLASSPATH b) Existing configuration for the application. Based on these, Spring Boot provides basic configuration needed to configure the application with these frameworks. This is called Auto Configuration.

If we want to find out more about what Auto Configuration is happening, we can turn on debuy logging. In application.properties, changing the logging level from INFO to DEBUG.

logging.level.org.springframeword: DEBUG

Automatic Configuration is one of the important things why Spring Boot is so famous and so easy to use.

6. Spring, Spring MVC and Spring Boot

great_explanation

6.1 Spring Framework

The core problem Spring framework solves is testability. If you don’t define proper dependencies then your applications are not testable. The most important feature of Spring Framework is Dependency Injection. The core of all Spring Modules is IOC,Inversion of Control.

What is IOC?
That is Spring Framework takes control of all beans and their dependencies. That’s basically what the Spring Framework cares about.

Why IOC or DI is important?
Because, when DI or IOC is used properly, we can develop loosely coupled applications. And loosely coupled application can be easily unit tested.

More about DI and IOC

What does Spring Framework Solve?
Spring Framework is all about defining your beans, putting your @Component, putting your @Service and things like that and also defining your dependencies @autowired and also defining how to find your beans, Component scan for example. That’s basically the core problem that Spring framework solves. Spring Framework solves the problem of dependency injection. It helps you to build loosely coupled application. Loosely coupled applications can be easily unit tested.

What else does Spring Framework Solve?

  • Duplication / Plumbing Code

For example, let’s say we are using JDBC then we need to write a lot of boilerplate code, try, catch, exception and all that kind of stuff. That’s not needed when you use any of the things that are based on the Spring framewords, Spring JDBC,… So Spring Frameworks help to reduce boilerplate code or reduce duplication and promote decoupling or increase uint testability.

  • Good Integration with Other Frameworks.

Great things about Spring Framework is that it does not try to solve things that are already solved. All that it does is to provide a great integration with frameworks which provide great solutions. Such as,
- Hibernate for ORM
- MyBatis for Object Mapping
- JUnit & MOckito for Unit Testing

6.2 Spring MVC

What is the Core Problem that Spring MVC Framework Solves?

Spring MVC Framework provides decoupled way of developing web applications. With simple conceptes like Dispatcher Servlet, ModelAndView and View Resolver, it makes it easy to develop web applications.

One of the great thing about Spring MVC is the separation of concerns.

  • Dispatchers servelt is concerned with just the basic front controller part.
  • ModelAndView holds both the model and view.
  • View Resolver is concerned with resolving a view name to the physical view.
    The handler returns the ModelAndView Object and DispatcherServlet resolves the view using View Resolvers and View.
More about Model, ModelMap and ModelAndView in Spring

6.3 Spring Boot

Spring based applications have a lot of configuration.
When we use Spring MVC, we need to configure component scan, dispatcher servlet, a view resolver, web jars(for delivering static content) among other things, like dataSource, transactionManager.

Spring Boot thinks can we bring more intelligence into this? When a spring mvc jar is added into an application, can we auto configure some beans automatically?

Why do we need Spring Boot

  • Spring Boot Auto Configuration.
  • Spring Boot Starter Projects: Built arount well known patterns.

Other Goals of Spring Boot

Spring Boot aims to enable production ready applications in quick time.

  • Actuator: Enables Advanced Monitoring and Tracing of applications.
  • Embedded Server Integrations: Since the server is integrated into the application, I would need to have a separate application server installed on the server.
  • Default Error Handling

7. Spring Boot Starter Projects - Starter Web and Starter JPA

What is Starter?

Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project, and you are good to go.

For example, spring-boot-starter-web.
If we want to develop a web application or an application to expose RESTful services, spring-boot-starter-web is the starter to pick.

Dependecncy of spring-boot-starter-web is

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

The following screenshot shows the different dependencies that are added into our application

Dependencies can be classified into:

  • Spring: core, beans, context, aop
  • Web MVC: (Spring MVC) spring-web, spring-webmvc
  • Jackson: for JSON Binding, spring-boot-starter-json(for RESTful services)
  • Validation: Hibernate Validator, Validation API, hibernate-validator
  • Embedded Servlet Container: Tomcat, spring-boot-starter-tomcat
  • Logging: logback, slf4j

Any typical web application would use all these dependencies. Spring Boot Starter Web comes pre-packaged with these. As a developer, I would not need to worry about either these dependencies or their compatible versions.

8. Overview of Different Spring Boot Starter Projects

As we see from Spring Boot Starter Web, starter projects help us in quickly getting started with developing specific types of applications.

  • spring-boot-starter-web-services: SOAP Web Services. If you want to define WSDL and then implement your web service, that’s a SOAP web service.
  • spring-boot-starter-web: Web and RESTful applications.
  • spring-boot-starter-test: Unit testing and Integration Testing.
  • spring-boot-starter-jdbc: Traditional JDBC
  • spring-boot-starter-hateoas: Add HATEOAS features to your services
  • spring-boot-starter-security: Authentication and Authorization using Spring Security
  • spring-boot-starter-data-jpa: Spring Data JPA with Hibernate
  • spring-boot-starter-cache: Enabling Spring Framework’s caching support
  • spring-boot-starter-data-rest: Expose Simple REST Services using Spring Data REST

There are a few starters for technical stuff as well

  • spring-boot-starter-actuator: To use advanced features like monitoring and tracing to your application out of the box
  • spring-boot-starter-undertow, spring-boot-starter-jetty, spring-boot-starter-tomcat: To pick your specific choice of Embedded Servlet Container
  • spring-boot-starter-logging: For Logging using logback
  • spring-boot-starter-log4j2: Logging using Log4j2

9. Spring Boot Actuator

It brings in a lot of monitoring around your application.

10. Spring Boot Developer Tools

How can I get the whole thing to be loaded automatically as soon as I make a code change? That’s where spring-boot-devtools comes in.

To use it, import its dependency.

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

   Reprint policy


《Spring Boot Introduction》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC