Session 4 SpringBoot
Session 4 SpringBoot
What is SpringBoot
:
Spring
Boot provides a good platform for Java developers to develop a stand-alone and
production-grade spring application that you can just run. You can
get started with minimum configurations without the need for an entire Spring
configuration setup.
Advantages of
springboot :
- Easy to understand and develop
spring applications
- Increases productivity
- Reduces the development time
Goals
- To avoid complex XML
configuration in Spring
- To develop a production ready
Spring applications in an easier way
- To reduce the development time
and run the application independently
- Offer an easier way of getting
started with the application
Why
to use springboot :
·
It
provides a flexible way to configure Java Beans, XML configurations, and
Database Transactions.
·
It
provides a powerful batch processing and manages REST endpoints.
·
In
Spring Boot, everything is auto configured; no manual configurations are
needed.
·
It
offers annotation-based spring application
·
Eases
dependency management
·
It
includes Embedded Servlet Container
How does it work?
Spring Boot automatically configures your application based on the
dependencies you have added to the project by using @EnableAutoConfiguration annotation.
For example, if MySQL database is on your classpath, but you have not
configured any database connection, then Spring Boot auto-configures an
in-memory database.
The entry point of the spring boot application is the class
contains @SpringBootApplication annotation and the main
method.
Auto Configuration :
Spring Boot Auto Configuration automatically configures your Spring
application based on the JAR dependencies you added in the project.
For this purpose, you need to add @EnableAutoConfiguration annotation
or @SpringBootApplication annotation to your main class file.
Then, your Spring Boot application will be automatically configured.
Observe the following code for a better understanding −
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Steps to create spring-boot project in sts ide
Step
1: Open the Spring Tool Suite.
Step
2: Click on the File menu -> New -> Maven Project
It shows the New Maven Project wizard. Click
on the Next button.
Step
3: select the check box of create a simple project then click next.
Step
4: Provide the Group
Id and Artifact Id. We have provided
Group Id com.consyosoft and Artifact Id spring-boot-pro Now click on the Finish button.
When we click on the Finish button, it
creates the project directory, as shown in the following image.
The Maven project has a pom.xml file which contains the following default
configuration.
pom.xml
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.consyosoft</groupId>
<artifactId>spring-boot-pro1</artifactId>
<version>0.0.1-SNAPSHOT</version>
</project>
Step
5: Add Java version inside
the <properties> tag.
<java.version>1.8</java.version>
Step
6: In order to make a Spring Boot Project, we need to configure it.
So, we are adding spring boot starter
parent dependency in pom.xml file. Parent is
used to declare that our project is a child to this parent project.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<type>pom</type>
</dependency>
Step
7: Add the spring-boot-starter-web dependency
in pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
1.1.1.1 Note: When we add the dependencies in the pom file, it
downloads the related jar file. We can see the downloaded jar files in the
Maven Dependencies folder of the project directory.
After adding all the dependencies, the
pom.xml file looks like the following:
pom.xml
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.consyosoft</groupId>
<artifactId>spring-boot-pro1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
</dependencies>
</project>
Step
8 : Create a package com.consyosoft under src/main/java,
create a class with the name App1
in
the package .
Step
10: After creating the class file, call the static method run() of the SpringApplication class. In the following
code, we are calling the run() method and passing the class name as an
argument.
SpringApplication.run(App1.class, args);
Step
11: Annotate the class by adding an annotation @SpringBootApplication.
@SpringBootApplication
A single @SpringBootApplication annotation is
used to enable the following annotations:
- @EnableAutoConfiguration: It
enables the Spring Boot auto-configuration mechanism.
- @ComponentScan: It
scans the package where the application is located.
- @Configuration: It
allows us to register extra beans in the context or import additional
configuration classes.
SpringBootApplicationSts.java
Step
12: Run the file App1.java, as Java
Application. It displays the following in the console.
The line Started APP1 in 4.592 seconds (JVM running for 5.399) in the console
shows that the application is up and running.
Spring
boot starters :
Handling dependency management is a difficult task for big projects.
Spring Boot resolves this problem by providing a set of dependencies for
developers convenience.
For example, if you want to use Spring and JPA for database access, it
is sufficient if you include spring-boot-starter-data-jpa dependency
in your project.
Note that all Spring Boot starters follow the same naming pattern spring-boot-starter- *,
where * indicates that it is a type of the application.
Examples
Look at the following Spring Boot starters explained below for a better
understanding −
Spring Boot Starter Actuator dependency is used to
monitor and manage your application. Its code is shown below −
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId></dependency>Spring Boot Starter Security dependency is used for
Spring Security. Its code is shown below −
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>Spring Boot Starter web dependency is used to
write a Rest Endpoints. Its code is shown below −
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>Springboot cli:
The Spring Boot CLI is a Command Line Interface for Spring
Boot. It can be used for a quick start with Spring. It can run Groovy scripts
which means that a developer need not write boilerplate code; all that is
needed is focus on business logic. Spring Boot CLI is the fastest way to create
a Spring-based application.
Features
·
It
provides an interface to run and test Spring Boot Application from command
prompt.
·
It
internally use Spring Boot Starter and Spring Boot AutoConfigurate components
in order to resolve all dependencies and executes the application.
·
It
contains Groovy compiler and Grape Dependency Manager.
·
It
supports Groovy Scripts without external Groovy installation.
·
It
adds Spring Boot defaults and resolve all dependencies automatically.
Spring is a Java-based framework; hence, we need to set up JDK first.
Following are the steps needed to setup Spring Boot CLI along with JDK
installation.
Step 1 - Setup Java
Development Kit (JDK)
You can download the latest version of SDK from Oracle's Java site
− Java SE
Downloads. You will find instructions for installing JDK in
downloaded files, follow the given instructions to install and configure the
setup. Finally set PATH and JAVA_HOME environment variables to refer to the
directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and have installed the JDK in C:\jdk1.6.0_15,
you would have to put the following line in your C:\autoexec.bat file
−
set PATH=C:\jdk1.6.0_15\bin;%PATH% set JAVA_HOME=C:\jdk1.6.0_15 Alternatively, on Windows NT/2000/XP, you will have to
right-click on My Computer, select Properties → Advanced → Environment
Variables. Then, you will have to update the PATH value and click the OK
button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_15 and
you use the C shell, you will have to put the following into your .cshrc file
−
setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.6.0_15 Step 2 - Install
Spring Boot CLI
You can download the latest version of Spring Boot CLI API as ZIP
archive from https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/.
Once you download the installation, unpack the zip distribution into a
convenient location. For example, in E:\Test\spring-1.5.8.RELEASE on
Windows, or /usr/local/spring-1.5.8.RELEASE on Linux/Unix.
Make sure you set your CLASSPATH variable on this directory properly
otherwise you will face a problem while running your application.
Or set the path in command prompt temporarily to run the spring boot
application as shown below −
E:/Test/> set path=E:\Test\spring-1.5.8.RELEASE\bin;%PATH%Step 3 - Verify
installation
Run the following command on command prompt to verify the installation −
E:/Test/> spring --versionIt should print the following output confirming the successful
installation −
Spring CLI v1.5.8.RELEASEwe'll create a Spring Boot + MVC + Rest based Web application.
Step 1: Create source
Folder
Create a folder FirstApplication in E:\Test folder.
Step 2: Create Source
File
Create FirstApplication.groovy file in E:\Test folder with
following source code −
@RestController
class FirstApplication {
@RequestMapping("/")
String welcome() {
"Welcome to TutorialsPoint.Com"
}
}
Step 3: Run the
application
Type the following command −
E:/Test/> spring run FirstApplication.groovyNow Spring Boot CLI will come into action, download required
dependencies, run the embedded tomcat, deploy the application and start it. You
can see the following output on console −
Resolving dependencies.................................................................................................................................................................. . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _> | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.8.RELEASE) 2017-11-07 17:36:55.703 INFO 5528 --- [ runner-0] o.s.boot.SpringApplication: Starting application on ...2017-11-07 17:36:55.707 INFO 5528 --- [ runner-0] o.s.boot.SpringApplication: No active profile set, falling back to default profiles: default2017-11-07 17:36:56.067 INFO 5528 --- [ runner-0] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4c108392: startup date [Tue Nov 07 17:36:56 IST 2017]; root of context hierarchy2017-11-07 17:36:57.327 INFO 5528 --- [ runner-0] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)2017-11-07 17:36:57.346 INFO 5528 --- [ runner-0] o.apache.catalina.core.StandardService : Starting service [Tomcat]2017-11-07 17:36:57.354 INFO 5528 --- [ runner-0] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.232017-11-07 17:36:57.537 INFO 5528 --- [ost-startStop-1] org.apache.catalina.loader.WebappLoader : Unknown loader org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader@41bfad4f class org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader2017-11-07 17:36:57.567 INFO 5528 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext2017-11-07 17:36:57.567 INFO 5528 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1500 ms2017-11-07 17:36:57.725 INFO 5528 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]2017-11-07 17:36:57.730 INFO 5528 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]2017-11-07 17:36:57.730 INFO 5528 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]2017-11-07 17:36:57.730 INFO 5528 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]2017-11-07 17:36:57.730 INFO 5528 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]2017-11-07 17:36:58.012 INFO 5528 --- [ runner-0] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4c108392: startup date [Tue Nov 07 17:36:56 IST 2017]; root of context hierarchy2017-11-07 17:36:58.066 INFO 5528 --- [ runner-0] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String FirstApplication.home()2017-11-07 17:36:58.070 INFO 5528 --- [ runner-0] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.map> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)2017-11-07 17:36:58.071 INFO 5528 --- [ runner-0] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)2017-11-07 17:36:58.096 INFO 5528 --- [ runner-0] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2017-11-07 17:36:58.096 INFO 5528 --- [ runner-0] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2017-11-07 17:36:58.129 INFO 5528 --- [ runner-0] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2017-11-07 17:36:58.626 INFO 5528 --- [ runner-0] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup2017-11-07 17:36:58.696 INFO 5528 --- [ runner-0] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)2017-11-07 17:36:58.699 INFO 5528 --- [ runner-0] o.s.boot.SpringApplication : Started application in 3.529 seconds (JVM running for 190.196)2017-11-07 17:37:20.217 INFO 5528 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'2017-11-07 17:37:20.218 INFO 5528 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started 2017-11-07 17:37:20.238 INFO 5528 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 20 ms</java.util.mapStep 4: Browse the
application in Browser
Our spring based rest application is now ready. Open url as "http://localhost:8080/"
and you will see the following output −
Hello WorldImportant points
Consider the following points to understand how Spring CLI works.−
·
All dependency JARs are downloaded for the first time
only.
·
Spring CLI automatically detects which dependency JARs
are to be downloaded based on the classes and annotations used in code.
·
Finally after the compilation of the code, deploy the war
file on an embedded tomcat and start embedded tomcat server on the default port
8080.
Gradle plugin :
The Spring
Boot Gradle Plugin provides Spring Boot support
in Gradle. It allows you to package executable jar or war archives,
run Spring Boot applications.
Overview
In this article, We are going explain how to create spring boot Gradle application or Spring boot Gradle Example. Gradle is very
popular build tool as like maven. Here we have created spring boot Gradle
application with Intellj IDE. Here is
guild how to create java application with Gradle.
Example
Here in the example, we have gradlew.bat (for windows), gradlew(for Linux) and gradle\wrapper to build and run Gradle
application which will be automatically created while creating Gradle
application IDE. We can also add those files using the command line here is
documentation for add wrapper files.
Spring
boot Gradle example
build.gradle
Location of build.gradle must be at the
root of the application that we can see in above project structure. Read
comment for each configuration requirements:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.9.RELEASE") // spring boot gradle plugin will used for generate jar
}
}
repositories {
mavenCentral()
}
description = "Spring boot Gradle Example"
apply plugin: 'java' // plugin for java
apply plugin: 'org.springframework.boot' //
plugin for spring boot framework
jar {
baseName = 'spring-boot-gradle-example' //
jar file name
version = '1.0.0' // application version
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web") // web application dependency
}
sourceCompatibility = 1.8 // for Java 1.8
targetCompatibility = 1.8
group 'spring-boot-demo'
version '1.0-SNAPSHOT'
1.1.2
2.2
application.properties
application.properties file contains properties related to spring boot
application. make sure that application.properties file bust inside resources folder.
server.port=8181
1.1.3
2.3
SpringBootApplication
package com.javadeveloperzone;
import org.springframework.boot.SpringApplication;
@org.springframework.boot.autoconfigure.SpringBootApplication
public class SpringBootApplication {
public static void main(String[] args){
SpringApplication.run(SpringBootApplication.class);
}
}
2.4 DemoController
Spring Controller which will handle a request for /hello
package com.javadeveloperzone;
import
org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@RequestMapping(value = "hello")
public String hello(){
return "Spring boot Gradle Example";
}
}
1.1.3.1
Clean & Build
Gradle Spring Boot Application
> gradlew clean build (It requires wrapper
in the project like gradlew.cmd(Windows) and gradlew(Linux))
or
> gradle clean build (Gradle must be
installed in the machine)
It will create jar file at \build\libs.
Starting a Gradle Daemon (subsequent builds will be faster)
:clean UP-TO-DATE
:compileJava
:processResources
:classes
:findMainClass
:jar
:bootRepackage
:assemble
:compileTestJava NO-SOURCE
:processTestResources NO-SOURCE
:testClasses UP-TO-DATE
:test NO-SOURCE
:check UP-TO-DATE
:build
Run
Spring boot Application
> gradlew bootRun (It requires
wrapper in the project like gradlew.cmd(Windows) and gradlew(Linux))
or
> gradle bootRun (Gradle must be
installed in the machine)
:compileJava
<-------------> 0% EXECUTING
> IDLE
:processResources
:classes
:findMainClass
:bootRun
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.9.RELEASE)
2018-04-28 11:02:50.463 INFO 141760 --- [ main] c.j.SpringBootApplication : Starting
SpringBootApplication on Mahesh with PID 141760
(F:\extrawork\spring-boot\spring-boot-gradle-example\build\cl
asses\main started by Lenovo in
F:\extrawork\spring-boot\spring-boot-gradle-example)
2018-04-28 11:02:54.576 INFO 141760 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer :
Tomcat started on port(s): 8181 (http)
2018-04-28 11:02:54.587 INFO 141760 --- [ main] c.j.SpringBootApplication : Started
SpringBootApplication in 4.65 seconds (JVM running for 5.202)
Our spring application is running on 8181 port, Let’s call web service:
http://localhost:8181/hello

Spring
boot Gradle example – output
1.2
3. Conclusion
In this article, We have seen how can quick start with Spring boot Gradle
Application with example. Gradle is a replacement for Maven.
application
class :
SpringApplication class is used to bootstrap and
launch a Spring application from a Java main method. This class automatically
creates the ApplicationContext from the classpath, scan the
configuration classes and launch the application. This class is very helpful in
launching Spring MVC or Spring REST application using Spring Boot.
Spring Boot Application
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. @SpringBootApplication annotation
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 @SpringBootApplication annotation 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 DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Component Scans in springboot
Spring Boot application
scans all the beans and package declarations when the application initializes.
You need to add the @ComponentScan annotation for your class
file to scan your components added in your project.
Observe the following code
for a better understanding −
import
org.springframework.boot.SpringApplication;
import
org.springframework.context.annotation.ComponentScan;
@ComponentScan
public
class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Configuration
annotation in springboot :
Use @Configuration annotation on top of any class to declare that this
class provides one or more @Bean methods and may
be processed by the Spring container to generate bean definitions and service
requests for those beans at runtime.
Externalize
your configuration using application.properties
Properties files are used to keep ‘N’ number of properties in a single
file to run the application in a different environment. In Spring Boot,
properties are kept in the application.properties file under
the classpath.
The application.properties file is located in the src/main/resources directory.
The code for sample application.properties file is given below
−
server.port = 9090spring.application.name = demoserviceNote that in the code shown above the Spring Boot application
demoservice starts on the port 9090.
Externalized Properties
Instead of keeping the properties file under classpath, we can keep the
properties in different location or path. While running the JAR file, we can
specify the properties file path. You can use the following command to specify
the location of properties file while running the JAR −
-Dspring.config.location = C:\application.properties




Comments
Post a Comment