Spring Boot

Spring Boot help build stand-alone, production Spring Applications easily, less configuration then rapidly start new projects.

Features:

  • Stand-alone Spring applications
  • Embedded Serverlet Container: Tomcat, Jetty or Undertow.
  • Support ‘Starter’ POMs to make your Maven configuration easily ways.
  • Automatically configure Spring.
  • Provide production-ready features such as metrics, health checks and externalized configuration
  • No code generation, No requirement for XML configuration


< Spring Framework


SQL Databases

1. Configure DataSource

Spring Boot supports auto-configured DataSource if you use spring-boot-starter-jdbc or spring-boot-starter-data-jpa ‘starters’. Details configuration at application.properties file:

But How to configure 2 or Multi-Datasource?

Steps to do:
– Open application.properties, configure datasource’s info:

– Mark one of the DataSource with @Primary:

– Now they are ready to be injected:

>>> More details at: How to configure multi Postgres DataSources with Springboot

2. Using JdbcTemplate

Spring’s Jdbc Template is used to access and manipulate databases. Spring Boot provides auto-configuration JdbcTemplate bean. So we can easily inject it via @Autowire. Or using supported function: getJdbcTemplate() of Spring’s JdbcDaoSupport class:

>>> More details at: How to use Spring JDBC Template with Spring Boot for Postgres DataBase

3. Spring JPA and Spring Data

For persistence, SpringBoot provides @Entity anonation for scanning entities.

>>> Example to practice:
Spring JPA – One to Many Relationship
Spring JPA – Many to Many relationship

4. H2 Database

H2 database has small footprint (smaller than 1.5 MB) with low memory requirements. It supports for multiple schemas and standard SQL, JDBC API. We can use H2 with disk based or in-memory databases.

H2 can be built by following mode:
– Embedded mode (local connections)
– Server mode (remote connections)
– Mixed mode (local and remote connections)

With Embedded Mode, an application uses JDBC to create a H2 database within the same JVM so it’s very fast to exchange data.

How to configure it with SpringBoot?
-> Spring Boot has a built in H2 database, so We just add below dependency:

>>> More details at: Integrate H2 database with SpringBoot & Spring JPA in Embedded mode

If your project uses H2 database to develop and also enable Spring Security, then when accessing to H2 console path: /h2_console, an error Access Denied Page will be thrown.

Why?
-> By default, Spring Security will block /h2_console path of H2 database.
How to resolve it?
-> Solution is a simple configuration with Spring Security as below segment code:

http.csrf().disable(): disable CRSF.
http.headers().frameOptions().disable(): H2 database console runs inside a frame, So we need to disable X-Frame-Options in Spring Security.

>>> More details at: How to configure Spring Security to access H2 database console in Spring Boot project

NoSQL Technologies

1. MongoDB

MongoDB is an open-source NoSQL document database, written using C++. Spring Boot provides an spring-boot-starter-data-mongodb to work with MongoDB.

To define MongoDb configured beans, use:
MongoDbFactory: an interface for factories to create DB instances.
MongoOperations: an interface that specifies a basic set of MongoDB operations.

To define Document model, use @Document

>>> Example for details at: Spring MongoOperations to access MongoDB

2. Neo4j

Neo4j is a highly scalable, native graph database. Spring Boot supports Spring Neo4J configuration with module: spring-boot-starter-data-neo4j.

– Configuration for connecting to Neo4J:

– Create a Neo4J repository by extends GraphRepository, sample:

– Some annotations for Neo4j database:
@NodeEntity: Identifies a domain entity as being backed by a node in the graph.
@GraphId: Identifies the field in the domain entity which is to be mapped to the id property of its backing node in the graph.
@Relationship: purpose for creating relationship of entities in Neo4j.

>>> Example for more details at: Spring Neo4J

3. Gemfire

Spring Data REST provides a mechanics for creating and retrieving an Object from Gemfire storage.

Configuration steps:
– Use needed dependencies: spring-boot-starter-data-rest, spring-boot-starter-data-gemfire:

– Use annotation @Region for mapping data:

– Config CacheFactoryBean and LocalRegionFactoryBean:

– Create a Gemfire repository by extends CrudRepository interface:

>>> Example for more details at: How to create a SpringBoot Gemfire RestfulApi

4. Elasticsearch

Elasticsearch is a distributed, full-text search engine based on Lucene with JSON schema. SpringBoot provides a convenient way by supported dependency: spring-boot-starter-data-elasticsearch ‘Starter’.

– Using annotation: @Document(indexName = "javasampleapproach", type = "customer") to create a mapping model.

– The main part is how to connect with Elasticsearch server, We use interface ElasticsearchRepository that is supported by Spring Data:

– Use spring.data.elasticsearch.cluster-nodes to define elasticsearch’s cluster.

>>> More details at: How to start SpringBoot ElasticSearch using Spring Data

5. Apache Cassandra

Apache Cassandra database is a NoSql solution for scalability & high availability. SpringBoot provides a convenient way by supported dependency: spring-boot-starter-data-cassandra ‘Starter’.

Use @Table & @PrimaryKey to create mapping model:
@Table: identifies a domain object to be persisted to Cassandra as a table.
@PrimaryKey: identifies the primary key field of the entity.

Create a Cassandra repository:
– Need provide port, keyspace-name and contact-points properties for connection’s info, via spring.data.cassandra:

– Spring Data supports basic operations for Cassandra. But more limited than JPA repositories, so we need use @Query.

>>> More details at: How to start Spring Data Cassandra with SpringBoot

Spring MVC

1. XML REST service

– If on the classpath has Jackson XML extension (jackson-dataformat-xml), SpringBoot will be used to render XML responses.
– If jackson-dataformat-xml is not available, JAXB in JDK will be used with a required annotation @XmlRootElement in model

– GET requests must have Accept: text/xml header.
– POST requests must have Content-Type: text/xml header.

>>> More details at: How to create a SpringBoot XML REST Service

2. Multipart File Uploads

Upload files to Servlet containers, application need register a MultipartConfigElement class. But Spring Boot makes it more easy by automatically configure it.
– From upload form, we specify enctype="multipart/form-data":

– In Post Mapping method, we specify MultipartFile file request’s parameter:

We can handle limit of file’s size by spring.http.multipart config:
spring.http.multipart.max-file-size: limit total file size for each request.
spring.http.multipart.max-request-size: limit total request size for a multipart/form-data.

>>> More details at: How to upload MultipartFile with Spring Boot

HATEOAS

Spring HATEOAS project helps to create REST representations that follow HATEOAS (Hypertext as the Engine of Application State) principle.

1. HATEOAS

In general, HATEOAS principle implies that with each response, API should shows Clients appropriate information about the next potential steps or guide to deeper understanding itself.

For example, if client requests for specific Customer information:
http://localhost:8080/customers/68
The Service should provide link to get all Orders of that Customer in the response:

2. Spring HATEOAS

Spring HATEOAS provides a set of useful types to ease working with those.

Firstly, we need create a Link object:
– Way 1: using Spring HATEOAS ControllerLinkBuilder
– Way 2: using Spring HATEOAS EntityLinks

Then, add Link object to ResourceSupport object:
– Way 1: extending ResourceSupport class
– Way 2: using Resources (that extends ResourceSupport class)

Finally, just return YourClass object or Resource object to Client.

>>> More details at: How to start Spring HATEOAS RestAPI with Spring Boot

3. Spring HATEOAS Rest API with JQuery Ajax POST/GET

We’ll build a Spring Boot Application in that:
HATEOAS REST Service provides interface for interacting with Database.
– Client calls API by using JQuery Ajax POST/GET.

>>> More details at: Spring HATEOAS Rest API + JQuery Ajax POST/GET example | Spring Boot

4. Consume Spring HATEOAS Rest API using JQuery Ajax

We’ll build a Spring Boot Application in that:
HATEOAS REST Service provides interface for interacting with Database.
– Client calls API by using JQuery Ajax GET, consume HATEOAS REST Service above and displays Data.

>>> More details at: Consume Spring HATEOAS Rest API using JQuery Ajax example | Spring Boot

5. Consume Spring HATEOAS Rest API using AngularJS

HATEOAS REST Service provides interface for interacting with Database.
– Client calls API by using AngularJS, consume HATEOAS REST Service above and displays Data.

>>> More details at: Consume Spring HATEOAS Rest API using AngularJS example | Spring Boot

CORS

Cross-Origin-Resource-Sharing (CORS) is a W3C specification which defines how a browser should be allowed using script to access different origin than the origin it has been served. With CORS, we can specify what kind of cross domain requests are authorized in a flexible way, instead of using some less secured and less powerful hacks like IFRAME or JSONP.

1. Configure CORS using @CrossOrigin

>>> More details at: Spring CORS example using @CrossOrigin – Spring Boot

2. Global CORS Configuration using Java Config

Spring provides a way that uses Java Config applying for all REST Service Controllers in our project.
WebMvcConfigurerAdapter has addCorsMappings() method that we need to override to configure CORS:

>>> More details at: Spring Boot – CORS Support using Java Config

3. Global CORS Configuration using XML Config

Spring also provides a way that uses XML Config applying for all REST Service Controllers in our project:

>>> More details at: Spring Boot – CORS Support using XML Config

Logging

1. Log4j2

Apache Log4j2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback’s architecture.

To configure Log4j2 dependency with Spring Boot, we do 3 steps:
– Exclude logback from default log dependency of Spring Boot:

– Add Spring Web MVC dependency:

– Add Log4j2 dependency:

And create a file with special name: log4j2.xml under /src/main/resources folder:

>>> More details at: How to configure Apache Log4j2 with Spring Boot

2. Actuator Loggers Endpoint

Spring Boot 1.5.1 provides some new features. Among them, we have a new actuator loggers endpoint, which helps us to view and change logging level of application with the MVC endpoint.

– Start with spring-boot-starter-actuator

– Actuator endpoints help us to monitor and interact with our application. Spring Boot includes a number of built-in endpoints including Loggers Endpoint:

‘…‘ could be: TRACE, DEBUG, INFO, WARN, ERROR…

– We can change how this endpoint exposes by add some code to application.properties, in this example:

– View Logging Level:
Just make a HTTP GET request to /loggers/[our qualified name of package]. The JSON String result will be:

– Change Logging Level: We can issue a HTTP POST request to /loggers/[our qualified name of package] with the following JSON

>>> More details at: How to change logging level with the MVC endpoint – new Actuator Loggers Endpoint | Spring Boot

MicroService

1. Routing and Filtering

Netflix Zuul is a proxy solution to forward requests to microservices, Spring Cloud Netflix contains an embedded Zuul.

Step to start building a Zuul gateway:
– Add required dependencies:

– Configure MicroServices for routing:

– Enable Zuul Gateway by annotation @EnableZuulProxy:

Zuul has 4 filter types:
pre filters are executed before the request is routed.
route filters uses to route the request.
post filters are executed after the request has been routed.
error filters execute if an error occurs while handling the request.

zuul-gateway-1

For creating a filter, just extends ZuulFilter. Then need overview 4 functions:
public String filterType(): specify the type of a filter: (pre, route, post, error) by a String
public int filterOrder(): indicates the order to process this filter.
public boolean shouldFilter(): gives a condition to consider to execute the filter.
public Object run(): functionality of the filter.

>>> More details at: How to configure SpringBoot Zuul – Routing and Filtering

2. Spring Cloud Ribbon – Client Load Balancing

Spring Cloud Ribbon is a solution for Client Load Balancing.

Advantage & Disadvantage:
– Decentralized Load Balancing
– No bottle neck
– Resilent
– Data can be inconsistent

SpringBoot provides a convenient way by supported dependency: spring-cloud-starter-ribbon ‘Starter’.

Config Ribbon Client:

@RibbonClient is used to configure a Ribbon Client.

@LoadBalanced annotation is used to configure RestTemplate bean as a LoadBalancerClient.

>>> More details at: Client Load Balancing – Spring Cloud Ribbon + Spring Boot

Messaging

JMS – ActiveMQ

Spring JMS (Java Message Service) is a powerful mechanism to integrate in distributed system.
ActiveMQ is a Java Open Source, it is simple JMS solution for concurrent, consumers and producers architecture in integrated development.
Spring Boot will create a Connection Factory basing on those information automatically:

Use JmsTemplate for sending & receiving messages:
JmsConsumer

JmsProducer

>>> Example for details at: How to use Spring JMS with ActiveMQ – JMS Consumer and JMS Producer

Caching

Infinispan

Infinispan cache is a distributed in-memory key/value data store, it is a excellent cache for software system. For starting with SpringBoot, we need dependencies:

– In application.properties file, use spring.cache to define configuration of Infinispan:

– The infinispan.xml file is created under folder: /src/main/resources:

– Enable caching by annotation: @EnableCaching:

>>> More details at: Infinispan Cache Solution | Spring Boot

Traditional Deployment

Create a deployable war file

Step to do:
– Extends SpringBootServletInitializer
– Update build configuration

1. Extends SpringBootServletInitializer

2. Update build configuration=
– Update your build configuration: war
– Configure embedded servlet container dependency as provided

>>> More details at: How to deploy Spring Boot Web App War file to Tomcat Server with Maven build

Batch Application

Many business operations need to process with batch job for critical environment. Spring Batch is a lightweight framework to boot the batch application. To start SpringBatch by SpringBoot, using dependency:

Configure datasource for repository of SpringBatch Application by easy way:

Spring Boot provides @EnableBatchProcessing annotation for automatically enable Spring Batch:

To configure details of a Batch Job, we can use Java Config or XML config:
– Java config

– XML config

>>> More details at:
How to start with Spring Batch using Spring Boot – Java Config
Spring Batch XML Config with Spring Boot

Sending Email

Spring Framework provides JavaMailSender interface & Spring Boot provides auto-configuration for sending mail.
– Using spring-boot-starter-mail dependency.
– Configure spring.mail for JavaMailSender:

– Create a MailSender class:

>>> More Details at: How to configure JavaMailSender with SpringBoot

All Articles

>>> SPRING BOOT