SpringBoot

Spring Boot is an open source Java-based framework used to create a Micro Service. It is developed by Pivotal Team. It is easy to create a stand-alone and production ready spring applications. Spring Boot contains a comprehensive infrastructure support for developing a micro service and enables you to develop enterprise-ready applications

The entry point of the Spring Boot Application is the class
contains @SpringBootApplication annotation. This class should have the main method to run the Spring Boot application. @SpringBootApplicationannotation includes Auto- Configuration, Component Scan, and Spring Boot Configuration.
If you added @SpringBootApplication annotation to the class, you do not need to add the @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotation. The @SpringBootApplicationannotation includes all other annotations.
Observe the following code for a better understanding −
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoSprinBootApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoSprinBootApplication.class, args);
   }
}

Advantages of Spring Boot

  • Create stand-alone Spring applications that can be started using java -jar.
  • Embed Tomcat, Jetty or Undertow directly. You don't need to deploy WAR files.
  • It provides opinionated 'starter' POMs to simplify your Maven configuration.
  • It automatically configure Spring whenever possible.
  • It provides production-ready features such as metrics, health checks and externalized configuration.
  • Absolutely no code generation and no requirement for XML configuration.

Auto Configuration

Spring Boot Auto Configuration automatically configures your Spring application based on the JAR dependencies you added in the project. For example, if Oracle database is on your class path, but you have not configured any database connection, then Spring Boot auto configures an in-memory database. (If you are not using spring boot then you need to use @EnableAutoConfiguration annotation)

Why Spring Boot?

·      It provides a flexible way to configure Java Beans, and Database Transactions.
·      It offers annotation-based spring application
·      Eases dependency management
·      It includes Embedded Servlet Container
·      It provides a powerful batch processing and manages REST endpoints.
·      In Spring Boot, everything is auto configured; no manual configurations are needed.
Spring Boot starter template
Spring Boot starters are templates that contain a collection of all the relevant transitive dependencies that are needed to start a particular functionality. For example, If you want to create a Spring WebMVC application then in a traditional setup, you would have included all required dependencies yourself. It leaves the chances of version conflict which ultimately result in more runtime exceptions.
With Spring boot, to create MVC application all you need to import is spring-boot-starter-web dependency.
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Spring Boot Starters
Name
Description
spring-boot-starter-thymeleaf
It is used to build MVC web applications using Thymeleaf views.
spring-boot-starter-data-couchbase
This is used for Couchbase document-oriented database and Spring Data Couchbase.
spring-boot-starter-artemis
It is used for JMS messaging using Apache Artemis.
spring-boot-starter-web-services
It is used for Spring Web Services.
spring-boot-starter-mail
It is used to support Java Mail and Spring Framework's email sending.
spring-boot-starter-data-redis
It is used for Redis key-value data store with Spring Data Redis and the Jedis client.
spring-boot-starter-web
It is used for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
spring-boot-starter-data-gemfire
It is used to GemFire distributed data store and Spring Data GemFire.
spring-boot-starter-activemq
It is used to JMS messaging using Apache ActiveMQ.
spring-boot-starter-data-elasticsearch
It is used to Elasticsearch search and analytics engine and Spring Data Elasticsearch.
spring-boot-starter-integration
It is used for Spring Integration.
spring-boot-starter-test
It is used to test Spring Boot applications with libraries including JUnit, Hamcrest and Mockito.
spring-boot-starter-jdbc
It is used for JDBC with the Tomcat JDBC connection pool.
spring-boot-starter-mobile
It is used for building web applications using Spring Mobile.
spring-boot-starter-validation
It is used for Java Bean Validation with Hibernate Validator.
spring-boot-starter-hateoas
It is used to build hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS.
spring-boot-starter-jersey
It is used to build RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web.
spring-boot-starter-data-neo4j
It is used for Neo4j graph database and Spring Data Neo4j.
spring-boot-starter-data-ldap
It is used for Spring Data LDAP.
spring-boot-starter-websocket
It is used for building WebSocket. applications using Spring Framework?s WebSocket support.
spring-boot-starter-aop
It is used for aspect-oriented programming with Spring AOP and AspectJ.
spring-boot-starter-amqp
It is used for Spring AMQP and Rabbit MQ.
spring-boot-starter-data-cassandra
It is used for Cassandra distributed database and Spring Data Cassandra.
spring-boot-starter-social-facebook
It is used for Spring Social Facebook.
spring-boot-starter-jta-atomikos
It is used for JTA transactions using Atomikos.
spring-boot-starter-security
It is used for Spring Security.
spring-boot-starter-mustache
It is used for building MVC web applications using Mustache views.
spring-boot-starter-data-jpa
It is used for Spring Data JPA with Hibernate.
spring-boot-starter
It is used for core starter, including auto-configuration support, logging and YAML.
spring-boot-starter-groovy-templates
It is used for building MVC web applications using Groovy Templates views.
spring-boot-starter-freemarker
It is used for building MVC web applications using FreeMarker views.
spring-boot-starter-batch
It is used for Spring Batch.
spring-boot-starter-social-linkedin
It is used for Spring Social LinkedIn.
spring-boot-starter-cache
It is used for Spring Framework?s caching support.
spring-boot-starter-data-solr
It is used for the Apache Solr search platform with Spring Data Solr.
spring-boot-starter-data-mongodb
It is used for MongoDB document-oriented database and Spring Data MongoDB.
spring-boot-starter-jooq
It is used for jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc.
spring-boot-starter-jta-narayana
It is used for Spring Boot Narayana JTA Starter.
spring-boot-starter-cloud-connectors
It is used for Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku.
spring-boot-starter-jta-bitronix
It is used for JTA transactions using Bitronix.
spring-boot-starter-social-twitter
It is used for Spring Social Twitter.
spring-boot-starter-data-rest
It is used for exposing Spring Data repositories over REST using Spring Data REST.


Spring Boot production starters
Name
Description
spring-boot-starter-actuator
It is used for Spring Boot?s Actuator which provides production ready features to help you monitor and manage your application.
spring-boot-starter-remote-shell
It is used for the CRaSH remote shell to monitor and manage your application over SSH. Deprecated since 1.5.


Spring Boot technical starters
Name
Description
spring-boot-starter-undertow
It is used for Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat.
spring-boot-starter-jetty
It is used for Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat.
spring-boot-starter-logging
It is used for logging using Logback. Default logging starter.
spring-boot-starter-tomcat
It is used for Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web.
spring-boot-starter-log4j2
It is used for Log4j2 for logging. An alternative to spring-boot-starter-logging.

Spring Boot Application Properties
Spring Boot provides various properties which can be specified inside our project's application.properties file
Property
Default value
Description
banner.charset
UTF-8
It is used to set banner file encoding.
banner.location
classpath:banner.txt
It is used to set banner file location.
logging.file
It is used to set log file name. For example data.log.
spring.application.index
It is used to set application index.
spring.application.name
It is used to set application name.
spring.application.admin.enabled
false
It is used to enable admin features for the application.
spring.config.location
It is used to config file locations.
spring.config.name
application
It is used to set config file name.
spring.mail.default-encoding
UTF-8
It is used to set default MimeMessage encoding.
spring.mail.host
It is used to set SMTP server host. For example smtp.example.com.
spring.mail.password
It is used to set login password of the SMTP server.
spring.mail.port
It is used to set SMTP server port.
spring.mail.test-connection
false
It is used to test that the mail server is available on startup.
spring.mail.username
It is used to set login user of the SMTP server.
spring.main.sources
It is used to set sources for the application.
server.address
It is used to set network address to which the server should bind to.
server.connection-timeout
It is used to set time in milliseconds that connectors will wait for another HTTP request before closing the connection.
server.context-path
It is used to set context path of the application.
server.port
8080
It is used to set HTTP port.
server.server-header
It is used for the Server response header (no header is sent if empty)
server.servlet-path
/
It is used to set path of the main dispatcher servlet
server.ssl.enabled
It is used to enable SSL support.
spring.http.multipart.enabled
True
It is used to enable support of multi-part uploads.
spring.http.multipart.max-file-size
1MB
It is used to set max file size.
spring.mvc.async.request-timeout
It is used to set time in milliseconds.
spring.mvc.date-format
It is used to set date format. For example dd/MM/yyyy.
spring.mvc.locale
It is used to set locale for the application.
spring.social.facebook.app-id
It is used to set application's Facebook App ID.
spring.social.linkedin.app-id
It is used to set application's LinkedIn App ID.
spring.social.twitter.app-id
It is used to set application's Twitter App ID.
security.basic.authorize-mode
role
It is used to set security authorize mode to apply.
security.basic.enabled
true
It is used to enable basic authentication.

 

Booting Spring Boot: Can be done in the following ways

1.            Using Spring Initializer

2.            Using Spring Boot CLI

3.            Using STS IDE.

 

Creating Rest Endpoint

To write a simple Hello World Rest Endpoint in the Spring Boot Application main class file itself, follow the steps shown below −
·      Firstly, add the @RestController annotation at the top of the class.
·      Now, write a Request URI method with @RequestMappingannotation.
·      Then, the Request URI method should return the Hello World string.
Now, your main Spring Boot Application class file will look like as shown in the code given below −
package com.sathish.demo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class HelloSpringBootApplication {
   public static void main(String[] args) {
      SpringApplication.run(HelloSpringBootApplication.class, args);
   }
}

 

package com.sathish.demo.controller;
 
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
public class HelloController {
   @RequestMapping(value = "/", method=”GET”)
   public String hello() {
      return "Hello World";
   }
}

Inheriting the starter parent

We can configure our project to inherit from the spring-boot-starter-parent by simply setting as below.
<parent>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-parent</artifactId>  
    <version>2.0.0.BUILD-SNAPSHOT</version>  
</parent>  

Changing the Java version

We can easily set Java version for our project in the properties section as given below.
<properties>  
    <java.version>1.8</java.version>  
</properties>  

Adding Spring Boot Maven Plugin

We can include Maven plugin in our pom.xml file. It is used to package the project as an executable jar. We are adding it here.
<build>  
    <plugins>  
        <plugin>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-maven-plugin</artifactId>  
        </plugin>  
    </plugins>  
</build>

Spring Boot Actuator
Actuator is a sub-project of Spring Boot. Production ready feature to help you monitor and manage your application.
To add the actuator to a Maven based project, add the following ‘Starter’ dependency:
<dependencies>
       <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-actuator</artifactId>
       </dependency>
</dependencies>


{
    "status" : "UP",
    "diskSpace" : {
         "status" : "UP",
         "free" : 209047318528,
         "threshold" : 10485760
     }
}

Here we are not writing health controller, it automatically comes if we add actuator.

Endpoints

Actuator endpoints let you monitor and interact with your application. Spring Boot includes a number of built-in endpoints and lets you add your own.
ID
Description
Enabled by default
auditevents
Exposes audit events information for the current application.
Yes
beans
Displays a complete list of all the Spring beans in your application.
Yes
caches
Exposes available caches.
Yes
conditions
Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match.
Yes
configprops
Displays a collated list of all @ConfigurationProperties.
Yes
env
Exposes properties from Spring’s ConfigurableEnvironment.
Yes
flyway
Shows any Flyway database migrations that have been applied.
Yes
health
Shows application health information.
Yes
httptrace
Displays HTTP trace information (by default, the last 100 HTTP request-response exchanges).
Yes
info
Displays arbitrary application info.
Yes
integrationgraph
Shows the Spring Integration graph.
Yes
loggers
Shows and modifies the configuration of loggers in the application.
Yes
liquibase
Shows any Liquibase database migrations that have been applied.
Yes
metrics
Shows ‘metrics’ information for the current application.
Yes
mappings
Displays a collated list of all @RequestMapping paths.
Yes
scheduledtasks
Displays the scheduled tasks in your application.
Yes
sessions
Allows retrieval and deletion of user sessions from a Spring Session-backed session store. Not available when using Spring Session’s support for reactive web applications.
Yes
shutdown
Lets the application be gracefully shutdown.
No
threaddump
Performs a thread dump.
Yes

If your application is a web application (Spring MVC, Spring WebFlux, or Jersey), you can use the following additional endpoints:
ID
Description
Enabled by default
heapdump
Returns an hprof heap dump file.
Yes
jolokia
Exposes JMX beans over HTTP (when Jolokia is on the classpath, not available for WebFlux).
Yes
logfile
Returns the contents of the logfile (if logging.file or logging.path properties have been set). Supports the use of the HTTP Range header to retrieve part of the log file’s content.
Yes
prometheus
Exposes metrics in a format that can be scraped by a Prometheus server.
Yes

Eureka Server
Eureka Server is an application that holds the information about all client-service applications. Every Micro service will register into the Eureka server and Eureka server knows all the client applications running on each port and IP address. Eureka Server is also known as Discovery Server.
The code for Eureka server Spring Boot application class
package com.sathish.eurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
 
@SpringBootApplication
@EnableEurekaServer
public class EurekaserverApplication {
   public static void main(String[] args) {
      SpringApplication.run(EurekaserverApplication.class, args);
   }
}

The code for Eureka client Spring Boot application class
package com.sathish.eurekaclient;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
 
@SpringBootApplication
@EnableEurekaClient
public class EurekaclientApplication {
   public static void main(String[] args) {
      SpringApplication.run(EurekaclientApplication.class, args);
   }
}

Cloud Configuration Server
Spring Cloud Configuration Server is a centralized application that manages all the application related configuration properties
Add the @EnableConfigServer annotation in your main Spring Boot application class file. The @EnableConfigServer annotation makes your Spring Boot application act as a Configuration Server
Configuration server client
Add the @RefreshScope annotation to your main Spring Boot application. The @RefreshScope annotation is used to load the configuration properties value from the Config server.
Now, add the config server URL in your application.properties file and provide your application name.
Note − http://localhost:8888 config server should be run before starting the config client application.
spring.application.name = config-client
spring.cloud.config.uri = http://localhost:8888

Swagger2
Swagger2 is an open source project used to generate the REST API documents for RESTful web services. It provides a user interface to access our RESTful web services via the web browser.
The @EnableSwagger2 annotation is used to enable the Swagger2 for your Spring Boot application. @EnableSwagger2 is used in configuration file.

package com.sathish.springboot.restapi.config; 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;

/**
* @author Sathish
*
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.sathish.springboot.restapi.controller"))
.paths(regex("/rest.*")).build().apiInfo(metaData());
}

private ApiInfo metaData() {
ApiInfo apiInfo = new ApiInfo("Spring Boot REST API", "Spring Boot REST API for ABC company", "1.0",
"Terms of service",
new Contact("Sathish Kariyanna", "http://sathishkariyanna.blogspot.com/", "abc@gmail.com"),
"Apache License Version 2.0", "https://www.apache.org/licenses/LICENSE-2.0");
return apiInfo;
}
}

//in the controller code we can have some customizations
//@Api(value = "some company", description = "Employee description")
@ApiOperation(value = "View default employee")

Rest Template
Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods.


References

1 comment: