Nearby lessons

1 of 10

Spring Boot - Introduction

📌 What You Will Learn
  • Understand Spring Boot - Introduction
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring Boot - Introduction step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

SPRING BOOT

Spring Boot is an open source Java-based framework developed by Pivotal Team.

--> Spring Boot makes it easy to create stand-alone, production-grade Spring based

Applications that you can "just run".

--> Spring Boot provides production-ready features such as metrics, health checks and

externalized configuration.

--> It simplifies the bootstrapping and development of Spring Applications.

--> Spring Boot was designed on the top of existed Spring Framework to simplify and

speedup the spring based applications.

--> Spring Boot can be used to develop Spring based applications either by using JAVA or by

using Groovy.

--> Spring Boot Simplifies application development by having all configurations as defaults.

--> Spring Boot reduces application development time.

--> Spring Boot will improve Productivity.

--> Spring Boot will provide very simple approach to integrate Spring Boot Application with

its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.

--> Spring Boot follows "Opinionated Defaults Configuration" approach to reduce

Developer effort, that is,Spring Boot avoids writing lots of boilerplate Code,Annotations

and XML Configuration,...

--> Spring Boot provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test

our web applications very easily.

--> Spring Boot provides CLI (Command Line Interface) tool to develop and test Spring Boot

Applications from command prompt very easily and quickly.

--> Spring Boot 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.

--> Where In-Memory databases are the databases, they will be created when application

startup and it will be destroyed when application terminated.

EX: H2 Database.

--> In simple words, Spring Boot is the Existed Spring Framework with Embedded Web

Servers like Tomcat and Jetty with No XMl configurations and less Annotations.

SPRING BOOT FEATURES

To describe Spring Boot nature, Spring Boot has provided the following features.

1.SpringApplication

2.Externalized Configuration

  • Profiles
  • Logging
  • Internationalization
  • JSON
  • Developing Web Applications:
  • RSocket:

9.Security:

  • Working with SQL Databases:
  • Working with NoSQL Technologies:
  • Cache:

13.Messaging:

  • Calling REST Services with RestTemplate and WebClient:
  • Validations:
  • Sending Email:

17.Distributed Transactions with JTA:

18.Application events and listeners:

19.Admin features:

20.Properties Files

21.YAML Support:

22.Type-safe Configuration:

1.SpringApplication:

SpringApplication is a class, it provides a convenient way to bootstrap a Spring application

that is started from a main() method. SpringApplication has a static method run() to

execute Spring application.

EX:

class MyApp{

public static void main(String[] args) {

SpringApplication.run(MyApp, args);

}

}

When we run the above application then we will get the following output .

. ____ _ __ _ _

/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

\\/ ___)| |_)| | | | | || (_| | ) ) ) )

' |____| .__|_| |_|_| |_\__, | / / / /

=========|_|==============|___/=/_/_/_/

:: Spring Boot :: v2.2.0.BUILD-SNAPSHOT

019-04-31 13:09:54.117 INFO 56603 --- [ main] o.s.b.s.app.SampleApplication :

Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar

started by pwebb)

2019-04-31 13:09:54.166 INFO 56603 --- [ main]

ationConfigServletWebServerApplicationContext : Refreshing

org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicat

ionContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context

hierarchy

2019-04-01 13:09:56.912 INFO 41370 --- [ main] .t.TomcatServletWebServerFactory :

Server initialized with port: 8080

2019-04-01 13:09:57.501 INFO 41370 --- [ main] o.s.b.s.app.SampleApplication

: Started SampleApplication in 2.992 seconds (JVM running for 3.658)

If your application fails to start, registered FailureAnalyzers get a chance to provide a

dedicated error message and a concrete action to fix the problem. For instance, if you start

a web application on port 8080 and that port is already in use, you should see something

similar to the following message:

*

APPLICATION FAILED TO START

*

Description:Embedded servlet container failed to start. Port 8080 was already in use.

Action:Identify and stop the process that's listening on port 8080 or configure this

application to listen on another port.

2.Externalized Configuration:

--------------------------------------

Spring Boot is giving an option to use like to externalize our application configurations so

that we can work with the same application code in different environments. To provide

Externalizable configurations we can use properties files, YAML files, environment

variables, and command-line arguments,..

In Spring Boot appliocations, we are able to provide externalized configurations like

1.ServletConfig init parameters.

2.ServletContext init parameters.

3.JNDI attributes from java:comp/env.

4.Java System properties (System.getProperties()).

5.OS environment variables.

6.Profile-specific application properties outside of your packaged jar (application-

{profile}.properties and YAML variants).

  • PROFILES:

-----------------

Spring Profiles provide a way to segregate parts of your application configuration and make

it be available only in certain environments.

IN SPring Boot applications, we are able to provide profiles configuration either through

@Profile() annotation or through properties file or through Command Line Arguments.

EX: Through Annotation

@Configuration(proxyBeanMethods = false)

@Profile("production")

public class ProductionConfiguration {

// ...

}

EX: Through Properties file

spring.profiles.active=dev,hsqldb

EX: Through Command Line Arguments.

--spring.profiles.active=dev,hsqldb.

  • Logging

---------------

Spring Boot uses Commons Logging for all internal logging but leaves the underlying log

implementation open. Default configurations are provided for Java Util Logging, Log4J2,

and Logback. In each case, loggers are pre-configured to use console output with optional

file output also available.

  • Internationalization:

--------------------------------

Spring Boot supports localized messages so that your application can provide services to

users of different languages . By default, Spring Boot looks for the presence of a messages

resource bundle at the root of the classpath.

To provide Internationalization support we have to configure messages properties file base

name in application configuration file like below.

spring.messages.basename=messages,config.i18n.messages

spring.messages.fallback-to-system-locale=false

  • JSON

------------

Spring Boot provides integration with three JSON mapping libraries

  • Gson
  • Jackson
  • JSON-B

Spring Boot is using "Jackson" as the preferred and default library.

  • Developing Web Applications:

--------------------------------------------

Spring Boot is well suited for web application development.We can create a self-contained

HTTP server by using embedded Tomcat, Jetty, Undertow, or Netty.

Most web applications use the spring-boot-starter-web module to get up and running

quickly.

  • RSocket:

---------------

RSocket is a binary protocol for use on byte stream transports. It enables symmetric

interaction models via async message passing over a single connection.

The spring-messaging module of the Spring Framework provides support for RSocket

requesters and responders, both on the client and on the server side.

9.Security:

--------------

If Spring Security is on the classpath, then web applications are secured by default. Spring

Boot relies on Spring Security's content-negotiation strategy to determine whether to use

httpBasic or formLogin. To add method-level security to a web application, you can also

add @EnableGlobalMethodSecurity with your desired settings

  • Working with SQL Databases:

----------------------------------------------

The Spring Framework provides extensive support for working with SQL databases, from

direct JDBC access using JdbcTemplate to complete "object relational mapping"

technologies such as Hibernate. Spring Data provides an additional level of functionality like

creating Repository implementations directly from interfaces and using conventions to

generate queries from your method names.

  • Working with NoSQL Technologies:

------------------------------------------------------

Spring Data provides additional projects that help us access a variety of NoSQL

technologies, including:

1.MongoDB

2.Neo4J

3.Elasticsearch

4.Cassandra

5.Couchbase

6.LDAP

  • Cache:

----------------

--> The Spring Framework provides support for transparently adding caching to an

application. At its core, the abstraction applies caching to methods, thus reducing the

number of executions based on the information available in the cache.

--> The caching logic is applied transparently, without any interference to the invoker.

Spring Boot auto-configures the cache infrastructure as long as caching support is

enabled via the @EnableCaching annotation.

13.Messaging:

--------------------

--> The Spring Framework provides extensive support for integrating with messaging

systems, from simplified use of the JMS API using JmsTemplate to a complete

infrastructure to receive messages asynchronously.

--> Spring AMQP provides a similar feature set for the Advanced Message Queuing

Protocol.

--> Spring Boot also provides auto-configuration options for RabbitTemplate and

RabbitMQ.

--> Spring WebSocket natively includes support for STOMP messaging, and Spring Boot has

support for that through starters and a small amount of auto-configuration. Spring Boot

also has support for Apache Kafka.

  • Calling REST Services with RestTemplate and WebClient:

----------------------------------------------------------------------------------

Spring Framework has provided RestTemplate class to access remote Rest Services from

our machine, but, Spring Boot has provided RestSupportBuilder to create RestTemplate

instance as part of auto configurations.

If we want to use Web Client to call remote Rest Services then we have to use WebFlux

module.

  • Validations:

---------------------

Spring Boot is supporting Bean validations like Hibernate Bean Validations inorder to

validate data in bean objects.

  • Sending Email:

------------------------

The Spring Framework provides an easy abstraction for sending email by using the

JavaMailSender interface, and Spring Boot provides auto-configuration for it as well as a

starter module.

17.Distributed Transactions with JTA:

---------------------------------------------------

Spring Boot supports distributed JTA transactions across multiple XA resources by using

either an Atomikos or Bitronix embedded transaction manager. JTA transactions are also

supported when deploying to a suitable Java EE Application Server.

When a JTA environment is detected, Spring's JtaTransactionManager is used to manage

transactions. Auto-configured JMS, DataSource, and JPA beans are upgraded to support XA

transactions. You can use standard Spring idioms, such as @Transactional, to participate in

a distributed transaction. If you are within a JTA environment and still want to use local

transactions, you can set the spring.jta.enabled property to false to disable the JTA auto-

configuration.

18.Application events and listeners:

------------------------------------------------

Spring Boot uses events to handle variety of tasks. It allows us to create factories file that

are used to add listeners. we can refer it by using ApplicationListener key.

Always create factories file in META-INF folder like: META-INF/spring.factories

19.Admin features:

--------------------------

Spring Boot provides the facility to enable admin related features for the application. It is

used to access and manage application remotely. We can enable it by simply using

spring.application.admin.enabled property.

20.Properties Files:

--------------------------

Spring Boot provides rich set of Application Properties. So, we can use that in properties file

of our project. Properties file is used to set properties like: server-port = 8082 and many

others. It helps to organize application properties.

21.YAML Support:

--------------------------

It provides convenient way for specifying hierarchical configuration. It is a superset of JSON.

The SpringApplication class automatically support YAML. It is successful alternative of

properties.

22.Type-safe Configuration:

--------------------------------------

Strong type-safe configuration is provided to govern and validate the configuration of

application. Application configuration is always a crucial task which should be type-safe.

We can also use annotation provided by this library.

📝 Key Takeaways
  • Key ideas of Spring Boot - Introduction explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end