It is a Spring module which provides RAD (Rapid Application Development) feature to Spring framework.
It is used to create stand alone spring based application that you can just run because it needs very little spring configuration.
Spring Boot does not generate code and there is absolutely no requirement for XML configuration.
It uses convention over configuration software design paradigm that means it decrease the effort of developer.
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.
Prerequisite of Spring Boot
To create a Spring Boot application following are the prerequisites. In this tutorial, we will use Spring Tool Suite IDE.
Java 1.8
Gradle 2.3+ or Maven 3.0+
Spring Framework 5.0.0.BUILD-SNAPSHOT
An IDE (Spring Tool Suit) is recommended.
Spring Boot Features
Web Development
SpringApplication
Application events and listeners
Admin features
Externalized Configuration
Properties Files
YAML Support
Type-safe Configuration
Logging
Security
Web Development
It is well suited Spring module for web application development. We can easily create a self-contained HTTP server using embedded Tomcat, Jetty or Undertow. We can use the spring-boot- starter-web module to start and running application quickly.
SpringApplication
It is a class which provides the convenient way to bootstrap a spring application which can be started from main method. You can call start your application just by calling a static run() method.
publicstaticvoid main(String[] args){
SpringApplication.run(className.class, args);
}
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
Admin Support
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.
Externalized Configuration
Spring Boot allows us to externalize our configuration so that we can work with the same application in different environments. Application use YAML files to externalize configuration.
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.
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.
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.
Logging
Spring Boot uses Common logging for all internal logging. Logging dependencies are managed by default. We should not change logging dependencies, if there is no required customization is needed.
Security
Spring Boot applications are spring bases web applications. So, it is secure by default with basic authentication on all HTTP endpoints. A rich set of Endpoints are available for develop a secure Spring Boot application.
Spring Boot Project
There are multiple approaches to create Spring Boot project. We can use any of the following approach to create application.
Spring Maven Project
Spring Starter Project Wizard
Spring Initializr
Spring Boot CLI
Here for all the example, we are using STS (Spring Toll Suite) IDE to create project. You can download this IDE from official site of Spring framework.
------------------------------------------------
Create New Maven project:
click on create a simple project. Next
In pom.xml:
Add:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <properties> <java.version>1.8</java.version> </properties> Now update maven. on right click project-properties-project facets-update java to 1.6 and also select dynamic web module. package com.javatpoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootExample { public static void main(String[] args) { SpringApplication.run(SpringBootExample.class, args); }
} package com.javatpoint; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class WelcomeController { private WelcomeService service = new WelcomeService(); @RequestMapping("/welcome") public String welcome(){ return service.retriveWelcomeMessage(); } class WelcomeService{ public String retriveWelcomeMessage(){ //complex method return "Good Morning"; } }
}
run SpringBootExample as Java application (not run on Server)
Everytime you finish running application stop tomcat
go on browser and enter: localhost:8080\welcome to see the output
Add @Autowired and @Component to tell Spring to manage beans - Dependency Injection
Here we import WelcomeService. Just to check whether spring is able to scan component or not.
For this, WelcomeService is defined as follows in new package com.service and WelcomeService need to be public otherwise it is not visible to other class.
package com.service;
import org.springframework.stereotype.Component;
@Component
public class WelcomeService{
public String retriveWelcomeMessage(){
//complex method
return "Good Morning Updated.";
}
}
For this, SpringBootExample need to add @ComponentScan("com"). So that Spring will scan all the @components inside the package com. If spring find it will autowired it else it throws exception.
Spring Boot provides a number of “Starters” that let you add jars to your classpath. Our sample application has already used spring-boot-starter-parent in the parent section of the POM. The spring-boot-starter-parent is a special starter that provides useful Maven defaults. It also provides a dependency-managementsection so that you can omit version tags for “blessed” dependencies.
Other “Starters” provide dependencies that you are likely to need when developing a specific type of application. Since we are developing a web application, we add aspring-boot-starter-web dependency.
Here we didn't configure dispatcher servlet which are auto configured in spring boot
apache tomcat is automatically set as server.
Error page is improved.
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 technologies 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, include the spring-boot-starter-data-jpa dependency in your project.
The starters contain a lot of the dependencies that you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies.
What’s in a name
All official starters follow a similar naming pattern; spring-boot-starter-*, where * is a particular type of application. This naming structure is intended to help when you need to find a starter. The Maven integration in many IDEs lets you search dependencies by name. For example, with the appropriate Eclipse or STS plugin installed, you can press ctrl-space in the POM editor and type “spring-boot-starter” for a complete list.
As explained in the “Creating Your Own Starter” section, third party starters should not start with spring-boot, as it is reserved for official Spring Boot artifacts. Rather, a third-party starter typically starts with the name of the project. For example, a third-party starter project called thirdpartyproject would typically be named thirdpartyproject-spring-boot-starter.
The following application starters are provided by Spring Boot under the org.springframework.boot group:
Table 13.1. Spring Boot application starters
Name
Description
Pom
spring-boot-starter
Core starter, including auto-configuration support, logging and YAML
Spring Boot vs Spring MVC vs Spring - How do they compare?
What’s the problem Spring Framework solves?
Most important feature of Spring Framework is Dependency Injection. At the core of all Spring Modules is Dependency Injection or IOC Inversion of Control.
Why is this important? Because, when DI or IOC is used properly, we can develop loosely coupled applications. And loosely coupled applications can be easily unit tested.
Let’s consider a simple example:
Example without Dependency Injection
Consider the example below: WelcomeController depends on WelcomeService to get the welcome message. What is it doing to get an instance of WelcomeService? WelcomeService service = new WelcomeService();. It’s creating an instance of it. And that means they are tightly coupled. For example : If I create an mock for WelcomeService in a unit test for WelcomeController, How do I make WelcomeController use the mock? Not easy!
World looks much easier with dependency injection. You let the spring framework do the hard work. We just use two simple annotations: @Component and @Autowired.
Using @Component, we tell Spring Framework - Hey there, this is a bean that you need to manage.
Using @Autowired, we tell Spring Framework - Hey find the correct match for this specific type and autowire it in.
In the example below, Spring framework would create a bean for WelcomeService and autowire it into WelcomeController.
In a unit test, I can ask the Spring framework to auto-wire the mock of WelcomeService into WelcomeController. (Spring Boot makes things easy to do this with @MockBean. But, that’s a different story altogether!)
@ComponentpublicclassWelcomeService{//Bla Bla Bla}@RestControllerpublicclassWelcomeController{@AutowiredprivateWelcomeServiceservice;@RequestMapping("/welcome")publicStringwelcome(){returnservice.retrieveWelcomeMessage();}}
What else does Spring Framework solve?
It builds on the core concept of Dependeny Injection with a number of Spring Modules
Spring JDBC
Spring MVC
Spring AOP
Spring ORM
Spring JMS
Spring Test
For example, you need much less code to use a JDBCTemplate or a JMSTemplate compared to traditional JDBC or JMS.
Problem 2 : Good Integration with Other Frameworks.
Great thing about Spring Framework is that it does not try to solve problems which are already solved. All that it does is to provide a great integration with frameworks which provide great solutions.
Hibernate for ORM
iBatis for Object Mapping
JUnit & Mockito for Unit Testing
What is the core problem that Spring MVC Framework solves?
Spring MVC Framework provides decoupled way of developing web applications. With simple concepts like Dispatcher Servlet, ModelAndView and View Resolver, it makes it easy to develop web applications.
Why do we need 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.
Spring Boot brings in new thought process around this.
It starts with Starter. Once you include Starter in your class path it will auto configure all the jars that you need.
Problem #2 : Spring Boot Starter Projects : Built around well known patterns
Let’s say we want to develop a web application.
First of all we would need to identify the frameworks we want to use, which versions of frameworks to use and how to connect them together.
All web application have similar needs. Listed below are some of the dependencies we use in our Spring MVC Course. These include Spring MVC, Jackson Databind (for data binding), Hibernate-Validator (for server side validation using Java Validation API) and Log4j (for logging). When creating this course, we had to choose the compatible versions of all these frameworks.
Here’s what the Spring Boot documentations says about starters.
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.
Let’s consider an example starter - Spring Boot Starter Web.
If you want to develop a web application or an application to expose restful services, Spring Boot Start Web is the starter to pick. Lets create a quick project with Spring Boot Starter Web using Spring Initializr.
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.
What else in Starter??
Spring Boot Starter Project Options
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
spring-boot-starter-web - Web & 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
Other Goals of Spring Boot
There are a few starters for technical stuff as well
spring-boot-starter-actuator - To use advanced features like monitoring & 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
Spring Boot aims to enable production ready applications in quick time.
Actuator : Enables Advanced Monitoring and Tracing of applications.
Embedded Server Integrations - Since server is integrated into the application, I would NOT need to have a separate application server installed on the server.
Default Error Handling
Spring Boot vs Spring
Spring
Spring is just a dependency injection framework. Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.
First half of the 2000 decade! EJBs
EJBs were NOT easy to develop.
Write a lot of xml and plumbing code to get EJBs running
Impossible to Unit Test
Alternative - Writing simple JDBC Code involved a lot of plumbing
Spring framework started with aim of making Java EE development simpler.
Goals
Make applications testable. i.e. easier to write unit tests
Reduce plumbing code of JDBC and JMS
Simple architecture. Minus EJB.
Integrates well with other popular frameworks.
Applications with Spring Framework
Over the next few years, a number of applications were developed with Spring Framework
Testable but
Lot of configuration (XML and Java)
Developing Spring Based application need configuration of a lot of beans!
Integration with other frameworks need configuration as well!
In the last few years, focus is moving from monolith applications to microservices. We need to be able to start project quickly. Minimum or Zero start up time
Framework Setup
Deployment - Configurability
Logging, Transaction Management
Monitoring
Web Server Configuration
Spring Boot
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.
We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss.
Example Problem Statements
You want to add Hibernate to your project. You dont worry about configuring a data source and a session factory. I will do if for you!
Goals
Provide quick start for projects with Spring.
Be opinionated but provide options.
Provide a range of non-functional features that are common to large classes of projects (e.g. embedded servers, security, metrics, health checks, externalized configuration).
What Spring Boot is NOT?
It’s not an app or a web server
Does not implement any specific framework - for example, JPA or JMS
Does not generate code
Creating a REST Service with Spring Boot
What is REST?
REST stands for REpresentational State Transfer. REST specifies a set of architectural constraints. Any service which satisfies these constraints is called RESTful Service.
The five important constraints for RESTful Web Service are
Client - Server : There should be a service producer and a service consumer.
The interface (URL) is uniform and exposing resources.
The service is stateless.
The service results should be Cacheable. HTTP cache, for example.
Service should assume a Layered architecture. Client should not assume direct connection to server - it might be getting info from a middle layer - cache.
Using appropriate Request Methods
Always use HTTP Methods. Best practices with respect to each HTTP method is described below:
GET : Should not update anything. Should be idempotent (same result in multiple calls). Possible Return Codes 200 (OK) + 404 (NOT FOUND) +400 (BAD REQUEST)
POST : Should create new resource. Ideally return JSON with link to newly created resource. Same return codes as get possible. In addition : Return code 201 (CREATED) is possible.
PUT : Update a known resource. ex: update client details. Possible Return Codes : 200(OK)
DELETE : Used to delete a resource.
Bootstrapping REST Services with Spring Initializr
Creating a REST service with Spring Initializr is a cake walk. We will use Spring Web MVC as our web framework.
Spring Initializr http://start.spring.io/ is great tool to bootstrap your Spring Boot projects.
Launch Spring Initializr and choose the following
Choose com.in28minutes.springboot as Group
Choose student-services as Artifact
Choose following dependencies
Web
Actuator
DevTools
Click Generate Project.
Import the project into Eclipse. File -> Import -> Existing Maven Project.
If you want to understand all the files that are part of this project, you can go here.
Now: Create Course Class.
packagecom.in28minutes.springboot.model;importjava.util.List;publicclassCourse{privateStringid;privateStringname;privateStringdescription;privateList<String>steps;// Needed by Caused by: com.fasterxml.jackson.databind.JsonMappingException:// Can not construct instance of com.in28minutes.springboot.model.Course:// no suitable constructor found, can not deserialize from Object value// (missing default constructor or creator, or perhaps need to add/enable// type information?)publicCourse(){}publicCourse(Stringid,Stringname,Stringdescription,List<String>steps){super();this.id=id;this.name=name;this.description=description;this.steps=steps;}publicStringgetId(){returnid;}publicvoidsetId(Stringid){this.id=id;}publicStringgetDescription(){returndescription;}publicStringgetName(){returnname;}publicList<String>getSteps(){returnsteps;}@OverridepublicStringtoString(){returnString.format("Course [id=%s, name=%s, description=%s, steps=%s]",id,name,description,steps);}@OverridepublicinthashCode(){finalintprime=31;intresult=1;result=prime*result+((id==null)?0:id.hashCode());returnresult;}@Overridepublicbooleanequals(Objectobj){if(this==obj)returntrue;if(obj==null)returnfalse;if(getClass()!=obj.getClass())returnfalse;Courseother=(Course)obj;if(id==null){if(other.id!=null)returnfalse;}elseif(!id.equals(other.id))returnfalse;returntrue;}}
Go to: https://jersey.github.io/download.html Jersey JAX-RS 2.1 RI bundle bundle contains the JAX-RS 2.1 API jar, all the core Jersey module jars as well as all the required 3rd-party dependencies.
Tomcat is an open source java application server provided by Apache, it is the most popular application server for java environment. 1. Prerequisite Tomcat doesn’t work without java, so before installing tomcat on the machine, you should install a compatible java runtime version and setup JAVA_HOME environment variable. Both java and tomcat versions should be compatible so i recommend to always install the same version for java and tomcat, in this tutorial we use java 8 and tomcat 8. 2. Installation Download the windows service installer from here : https://tomcat.apache.org/download-80.cgi Install the downloaded file, pass all the setup until reaching Configuration Options . here you can set the service name, the shutdown port and the running port of tomcat, by default tomcat runs on port 8080, so i recommend to keep the default configuration as it is, you can always change these configuration after the in...
REST - REpresentational State Transfer is a web based architecture and uses HTTP protocol for data communication. The following HTTP methods are commonly used in REST architecture: GET, PUT, DELETE, POST 1) Create "Dyanamic Web Project" - Add web.xml while creating Java Dynamic Web Project. 2) Import Jersey Jar file inside lib folder in WEB-INF. (Get Jersey Jar File from https://jersey.github.io/download.html)
Comments
Post a Comment