Spring Boot is a relatively new project in the Spring community. The purpose of this project is to help developers create Spring-based applications and services more easily, to allow more people to get started with Spring faster, and to enable Java development to achieve the same productivity as Ruby on Rails. Provides a fixed, convention-over-configuration style framework for the Spring ecosystem.
Spring Boot has the following features:
- Provides a faster onboarding experience for Spring-based development
- Out of the box, there is no code generation and no XML configuration required. It is also possible to modify the default values to meet specific needs.
- Provides some non-functional features common in large projects, such as embedded server, security, indicators, health detection, external configuration, etc.
- Spring Boot does not enhance the functionality of Spring, but provides a fast way to use Spring.
This article explains a piece of code in depth based on the official documentation
Simple example
Spring Boot recommends using Maven or Gradle. This article uses Maven as an example.
First create a general Maven project, with a pom.xml and basic src/main/java
structure.
pom.xml
Write the following in :
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.abel533</groupId>
<artifactId>spring-boot</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
The first is to increase<parent>
It is relatively simple to add a parent pom, and it spring-boot-starter-parent
includes a large number of configured dependency management. When adding these dependencies to your own project, you do not need to write the <version>
version number.
Although it is simple to use the parent pom, in some cases, we already have the parent pom, and <parent>
when it cannot be added directly, we can use the following methods:
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.2.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
java.version property
Although this attribute does not appear in the pom.xml above, it should be specially reminded here.
Spring uses jdk1.6 by default. If you want to use jdk1.8, you need to pom.xml
add it in the properties java.version
, as follows:
<properties>
<java.version>1.8</java.version>
</properties>
Add spring-boot-starter-web dependency
spring-boot-starter-*
Spring can support a specific function by adding such a dependency.
Our example is ultimately to implement web functionality, so this dependency is added.
A more complete list of features can be found here: using-boot-starter-poms
Add spring-boot-maven-plugin plugin
The plug-in supports a variety of functions, and there are two commonly used ones. The first one is to package the project into an executable jar package.
Executing in the root directory of the project mvn package
will generate an executable jar package, which contains all the dependent jar packages. Only this jar package is needed to run the program, which is very convenient to use. After the command is executed, a XXX.jar.original
jar package will be retained, which contains separate parts of the project.
After the executable jar package is generated, the java -jar xxxx.jar
project can be started by executing it on the command line.
Another command is mvn spring-boot:run
that you can use the tomcat
(default) startup project directly.
In our development process, we need to modify frequently, in order to avoid repeated project launch, we can enable hot deployment.
Spring-Loaded
The project provides a powerful hot deployment function, which can be hot deployed when adding/deleting/modifying methods/fields/interfaces/enumerations, which is very fast and convenient.
It's very simple to Spring Boot
use this function in the spring-boot-maven-plugin
plugin, just add a dependency below the plugin:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
</dependencies>
After adding, hot deployment is supported by mvn spring-boot:run
starting.
Note: When using hot deployment, the IDE needs to compile the class to take effect. You can turn on the automatic compilation function, so that the class will be automatically reloaded when you save the changes.
Create an application class
We create a Application
class:
@RestController
@EnableAutoConfiguration
public class Application {
@RequestMapping("/")
String home() {
return "Hello World!";
}
@RequestMapping("/now")
String hehe() {
return "现在时间:" + (new Date()).toLocaleString();
}
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
}
Notice
Spring Boot recommends configuring the main configuration classmain
where our method is located under the root package name.
Similar to the following structure:
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
There Application.java
are main
methods.
Because of the default package-related annotations, the default package name is the package where the current class is located, such as @ComponentScan, @EntityScan, @SpringBootApplication
annotations.
@RestController
Because our example is writing a web application, this annotation is written, which is equivalent to adding @Controller
and @ResponseBody
annotating at the same time.
@EnableAutoConfiguration
Spring Boot recommends only one class with this annotation.
@EnableAutoConfiguration
Role: Spring Boot will automatically configure the project according to the dependencies of your jar package. For example, when you HSQLDB
have , Spring Boot will create the default in-memory database data source DataSource
. If you create it yourself DataSource
, Spring Boot will not create the default one DataSource
.
If you don't want Spring Boot to create it automatically, you can configure the exclude
properties of the annotation, for example:
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
@SpringBootApplication
Since a large number of projects will add @Configuration,@EnableAutoConfiguration,@ComponentScan
three annotations to the main configuration class.
Therefore, Spring Boot provides @SpringBootApplication
annotations that can replace the above three annotations (using Spring annotation inheritance implementation).
home and other methods
@RequestMapping("/")
String home() {
return "Hello World!";
}
@RequestMapping("/now")
String hehe() {
return "现在时间:" + (new Date()).toLocaleString();
}
These methods are added @RequestMapping("xxx")
, and this annotation acts as a route.
Start the project SpringApplication.run
The easiest way to start a Spring Boot project is to execute the following method:
SpringApplication.run(Application.class, args);
This method returns an object, and the specific type returned is or when ApplicationContext
using annotations, and the second when web is supported.AnnotationConfigApplicationContext
AnnotationConfigEmbeddedWebApplicationContext
In addition to the above method, you can also use the following methods:
SpringApplication application = new SpringApplication(Application.class);
application.run(args);
SpringApplication
Contains some other configurable methods, if you want to do some configuration, you can use this way.
In addition to the direct method above, you can also use SpringApplicationBuilder
:
new SpringApplicationBuilder()
.showBanner(false)
.sources(Application.class)
.run(args);
When using SpringMVC, you need to use it because you need to use subcontainers. SpringApplicationBuilder
This class has a child(xxx...)
method to add subcontainers.
run
Execute the main method directly in the IDE, and then access it http://localhost:8080
.
In addition, you can also use the above mentioned mvn
, can be packaged as an executable jar package, and then executed java -jar xxx.jar
.
Or execute the mvn spring-boot:run
run project.
After the project starts, the following log is output:
[INFO] Attaching agents: [F:\.m2\repository\org\springframework\springloaded\1.2.5.RELEASE\springloaded-1.2.5.RELEASE.jar]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.2.3.RELEASE)
2015-12-12 22:26:35.298 INFO 9844 --- [ main] c.github.abel533.springboot.Application : Starting Application on liuzh-PC with PID 9844 (F:\Liu\IDEA\SpringBoot\spring-boot\target\classes started by liuzh_3nofxnp in F:\Liu\IDEA\SpringBoot\spring-boot)
2015-12-12 22:26:35.332 INFO 9844 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@a38d7a3: startup date [Sat Dec 12 22:26:35 CST 2015]; root of context hierarchy
2015-12-12 22:26:35.734 INFO 9844 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2015-12-12 22:26:36.302 INFO 9844 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2015-12-12 22:26:36.456 INFO 9844 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2015-12-12 22:26:36.457 INFO 9844 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.20
2015-12-12 22:26:36.537 INFO 9844 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2015-12-12 22:26:36.537 INFO 9844 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1207 ms
2015-12-12 22:26:36.941 INFO 9844 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2015-12-12 22:26:36.944 INFO 9844 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2015-12-12 22:26:36.945 INFO 9844 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2015-12-12 22:26:37.111 INFO 9844 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@a38d7a3: startup date [Sat Dec 12 22:26:35 CST 2015]; root of context hierarchy
2015-12-12 22:26:37.152 INFO 9844 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto java.lang.String com.github.abel533.springboot.Application.home()
2015-12-12 22:26:37.152 INFO 9844 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/now],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto java.lang.String com.github.abel533.springboot.Application.hehe()
2015-12-12 22:26:37.156 INFO 9844 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2015-12-12 22:26:37.156 INFO 9844 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2015-12-12 22:26:37.175 INFO 9844 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-12-12 22:26:37.175 INFO 9844 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-12-12 22:26:37.195 INFO 9844 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-12-12 22:26:37.237 INFO 9844 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2015-12-12 22:26:37.279 INFO 9844 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2015-12-12 22:26:37.280 INFO 9844 --- [ main] c.github.abel533.springboot.Application : Started Application in 2.181 seconds (JVM running for 2.607)
finally
The above is the basic content of Spring Boot. If there are some incomplete places or readers have more questions, you can view the full documentation of Spring Boot .
For more information about Spring Boot, you can continue to follow this blog.
I have a WeChat public account, and I often share some dry goods related to Java technology; if you like my sharing, you can use WeChat to search for "Java Head" or "javatuanzhang" to follow.