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


Contents

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

6. Couchbase

Spring Boot provides auto-configuration for Couchbase and abstractions on top of it by Spring Data Couchbase. We can use it easily via spring-boot-starter-data-couchbase ‘Starter’ which had collected the needed dependencies.

For connecting with Couchbase Bucket and Cluster, we can use spring.couchbase.* properties in application.properties file:

For working with Couchbase repository, we use CouchbaseRepository interface:

>>> More details at: Couchbase – How to create Spring JPA Couchbase application with SpringBoot

7. Solr

spring-data-solr-springboot-architecture

SpringBoot provides spring-boot-starter-data-solr Starter to support connecting and abstractions on top of Spring Data Solr.

7.1 Solr connection

In application.properties file, We use spring.data.solr.* to configure Solr connection.
Here is the details of sourcecode – SolrProperties:

By default the instance will attempt to connect to a server using http://localhost:8983/solr. And we can add @Bean with SolrClient type to override it.

7.2 Spring Data Solr repositories

We use @SolrDocument to create Solr document:

Using SolrCrudRepository to create Solr repositories:

Details about interface SolrCrudRepository:

>>> More details at: Apache Solr – How to start Spring Data Solr 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

I. ActiveMQ

1. JMS Producer/Consumer

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

2. Explicitly configure Spring ActiveMq ConnectionFactory

For configuring ActiveMQ ContainerFactory, we need to setup a new bean ConnectionFactory to override the auto-configured connection-factory bean of SpringBoot.

Then use the ConnectionFactory bean to configure 2 beans {JmsListenerContainerFactory, JmsTemplate}:

JmsTemplate bean is used to send Jms messages.
JmsListenerContainerFactory is used to listen Jms messages.

>>> More details at: ActiveMq – Explicitly configure Spring ActiveMq ConnectionFactory with SpringBoot

3. JMS ActiveMQ – Send Java object messages(specially with Bi-Directional relationship Java objects)

Use Jms MessageConverter bean as below:

With Bi-Directional Java object messages -> We got an Infinite recursion (StackOverflowError) exception:

-> We can use @JsonIdentityInfo to resolve it.

>>> More details at: Spring Jms ActiveMq – How to send Java object messages to ActiveMQ server (specially with Bi-Directional relationship Java objects)

4. JMS ActiveMq Topic (Publisher-Subcribers pattern)

ActiveMq provides the Publish-Subscribe pattern (pub-sub) for building Jms message distributed systems.
How it work? -> When you publish a messages, all active subscribers will receive a copy of the message:

ActiveMQ - Publisher/Consumer

With SpringBoot application, we need to enable pubSubDomain (.setPubSubDomain(true)) for 2 beans {JmsTemplate, JmsListenerContainerFactory}:

And set spring.jms.pub-sub-domain=true in application.properties file.

>>> More details at: ActiveMq – How to work with Spring JMS ActiveMq Topic (Publisher-Subcribers pattern) using SpringBoot

5. Response Management
5.1 @SendTo

With the Spring JMS improvements (from 4.1), we can used @SendTo annotation to define the default next destination with @JmsListener:

SpringBoot-ActivMQ-Response-Management-application-sendto-aannotation-architecture

For additional headers, you could return a Message object instead:

>>> More details at: Spring Jms ActiveMQ – How to create a SpringBoot ActiveMQ Response Management application by @SendTo annotation

5.2 JmsResponse

With the support of JmsResponse, we can configure the response destination at runtime:

SpringBoot-ActivMQ-Response-Management-application-JmsResponse-architecture-1

>>> More details at: Spring JMS ActiveMq – How to implement a runtime SpringBoot ActiveMQ JmsResponse application

II. Apache Artemis

SpringBoot Auto-configure
When having artemis-jms-client Artemis on the classpath, Spring Boot can auto-configure a ConnectionFactory.
We use spring.artemis.* to control Artemis configuration:

spring.artemis.mode has 2 mode: {NATIVE, EMBEDDED}:
NATIVE: Connect to a broker using the native Artemis protocol.
EMBEDDED: Embed the broker in the application.

For sending message, we use: JmsTemplate:

For recieved messages, we use: @JmsListener:

springboot-artemis-architecture

>>> More details at: Apache Artemis – How to produce/consume JMS messages with SpringBoot Artemis applications.

III. AMQP

1. RabbitMQ Producer/Consumer

Creating 2 SpringBoot applications {Producer, Consumer} for working with RabbitMQ:

rabbitmq-architecture-copyright

Producer will send messages to RabbitMQ Exchanges with a routingKey. RabbitMQ uses routingKey to determine which queues for routing messages.
Consumer listens on a RabbitMQ Queue to receive messages.

With SpringBoot, we use spring.rabbitmq.* for controlling RabbitMQ configuration:

Producer uses AmqpTemplate to send messages:

Consumer uses @RabbitListener to recieve messages:

>>> More details at: RabbitMQ – How to create Spring RabbitMQ Producer/Consumer applications with SpringBoot

2. RabbitMq Publish/Subcribe pattern

Flow messages:
Publisher will send messages to the fanout exchange.
– The fanout exchange routes messages to all of the queues that are bound to it and the routing key is ignored.
Subcribers instances recieves messages from the queues.

Spring-RabbitMq-Publish–Subscribe-pattern-architechture

>>> More details at: RabbitMq – How to create Spring RabbitMq Publish/Subcribe pattern with SpringBoot

3. RabbitMQ – send/receive Java object messages

Using Message Converter:

With Bi-Directional Java object messages -> We may get an Infinite recursion (StackOverflowError) exception.

-> Solution: we can use @JsonIdentityInfo to handle the exception.

>>> More details at: RabbitMQ – How to send/receive Java object messages with Spring RabbitMq | SpringBoot

IV. Apache Kafka

1. SpringBoot supports auto-configuration

SpringBoot supports auto-configuration for Apache Kafka development:
– Use spring.kafka.* in application.properties file to modify external configuration.

SpringBoot-Kafka-Application

– Use Spring auto-configured KafkaTemplate to send Kafka-based messages:

– Use @KafkaListener to setup a Kafka listener:

>>> More details at: How to start Spring Apache Kafka Application with SpringBoot Auto-Configuration

2. Spring Kafka JsonSerializer (JsonDeserializer) to produce/consume Java Object messages

We send and receive Java object messages to/from Apache Kafka, so ProducerFactory uses JsonSerializer.class and ConsumerFactory uses JsonDeserializer.class to serialize/deserialize Java objects to Json bytes.

KafkaProducerConfig:

KafkaConsumerConfig:

Note: SpringKafka uses Jackson library to serialize/de-serialize Java objects to/from Json bytes so we need jackson-databind dependency.

>>> More details at: How to use Spring Kafka JsonSerializer (JsonDeserializer) to produce/consume Java Object messages

Caching

1. 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

2. Couchbase

We can use Couchbase as backing cache:

spring-cache-couchbase-architecture-resize

How to configure Couchbase server as Cache?
-> We need to build a CacheManager with Couchbase cluster:

@EnableCaching is used to enable the caching.

Document for Couchbase cache is built with Serializable:

>>> More details at: Couchbase – How to create Spring Cache Couchbase application with SpringBoot

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

WebSocket

1. Flow of messages

We create a Spring WebSocket Application with the below flow of messages:

spring-websocket-architecture-new-ws

Detail explanations:
– WebSocket clients connect to the WebSocket endpoint at ‘/jsa-stomp-endpoint’
– Subscriptions to ‘/topic/hi’ pass through the response channel, then are forwarded to the In-memory broker (Simple Broker).
– User objects sent to ‘/jsa/hello’ pass through the request channel then are forwarded to the spring WebController. WebController will handle User objects by @MessageMapping and transform to Hello messages then use @SendTo returns the messages to ‘/topic/hi’ through the brokerChannel.

– The Simple Broker broadcasts messages to subscribers through the response channel.

2. Server side

In server side, we use SockJS and STOMP for our application.

What is SockJS?
-> SockJS lets applications use a WebSocket API but falls back to non-WebSocket alternatives when necessary at runtime, without the need to change application code.

Simple Java configuration to enable SockJS and Stomp in Spring application:

3. Client side

About client side, we uses {sockjs-client, stomp-websocket} libs for development:

– Make a connection:

The connect() function uses SockJS and stomp.js to open a connection to /jsa-stomp-endpoint, which is where our SockJS server is waiting for connections.

– Dis-Connection:

– Send messages:

>>> More details at: WebSocket – Create Spring WebSocket Application with SpringBoot + SockJS + STOMP

All Articles

>>> SPRING BOOT