一、Spring Boot 简述
Spring Boot致力于简化Spring 应用开发,消除了Spring 应用开发过程中大量的模板化配置。Spring Boot提供了四个主要特性,能够改变Spring应用程序的开发方式:
- Spring Boot Starter:它将Spring常用的依赖分组进行了整合,将其合并到一个依赖中,这样就可以一次性添加到项目的Maven或Gradle构建中。
- 自动配置:Spring Boot的自动配置特性利用了Spring4 对条件化配置的支持,能够合理推测到应用所需的Bean并自动配置它们
- 命令行接口:
- Actuator:提供里管理特性,能够观察到Spring应用内部运气情况,如端点、异常处理、应用信息等。
- 创建Maven Project
- 修改pom.xml设置parent为Spring Boot ,下面为修改后maven构建文件示例
<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.appqinan</groupId> <artifactId>appqinan</artifactId> <version>0.10</version> <name>appqinan</name> <description>appqinan</description> <!-- 继承自Spring Boot starter --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.1.4.RELEASE</version> </parent> <!-- 应用依赖 --> <dependencies> </dependencies> <!-- 构建jar文件 --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
<!-- 修改默认JDK版本 -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<?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.habuma</groupId>
<artifactId>contacts</artifactId>
<version>0.1.0</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
保存pom并刷新Maven,自此Spring MVC所需所有依赖都会添加到项目中。
4. 开发控制器
ContactController,一个简单的控制器,用于展现联系人表单的HTTP GET请求和处理表单的POST请求。
package contacts;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/")
public class ContactController {
private ContactRepository contactRepo;
@Autowired
public ContactController(ContactRepository contactRepo) {
this.contactRepo = contactRepo;
}
@RequestMapping(method=RequestMethod.GET)
public String home(Map<String,Object> model) {
List<Contact> contacts = contactRepo.findAll();
model.put("contacts", contacts);
return "home";
}
@RequestMapping(method=RequestMethod.POST)
public String submit(Contact contact) {
contactRepo.save(contact);
return "redirect:/";
}
}
5. 创建试图
示例使用Thymeleaf模板实现Spring MVC视图功能,程序清单添加home.htm模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot Contacts</title>
<link rel="stylesheet" th:href="@{/style.css}" />
</head>
<body>
<h2>Spring Boot Contacts</h2>
<form method="POST">
<label for="firstName">First Name:</label>
<input type="text" name="firstName"></input><br/>
<label for="lastName">Last Name:</label>
<input type="text" name="lastName"></input><br/>
<label for="phoneNumber">Phone #:</label>
<input type="text" name="phoneNumber"></input><br/>
<label for="emailAddress">Email:</label>
<input type="text" name="emailAddress"></input><br/>
<input type="submit"></input>
</form>
<ul th:each="contact : ${contacts}">
<li>
<span th:text="${contact.firstName}">First</span>
<span th:text="${contact.lastName}">Last</span> :
<span th:text="${contact.phoneNumber}">phoneNumber</span>,
<span th:text="${contact.emailAddress}">emailAddress</span>
</li>
</ul>
</body>
</html>
自动配置的模板解析器会在指定的目录下查找Thymeleaf模板,这个目录也就是相对于根类路径下的templates目录下,所以在项目中需要将home.html放到“src/main/ resources/templates”中。
6. 添加静态内容
当采用Spring Boot的Web自动配置来定义Spring MVC bean时,这些bean中会包含一个资源处理器(resource handler), 它会将“/**”映射到几个资源路径中。这些资源路径包括(相对于类路径的
根):
META-INFresources/
resources
static
public
示例是将html模板存放public中,不过上述4个方案是等价的。
7.持久化数据
示例采用JDBC和H2作为应用的持久层实现,Spring Boot JDBC Starter 依赖能将Spring JDBCTemplate所需依赖全部添加。使用H2还需要添加H2依赖。配置片段如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
当Sping Boot 在类路径中探测到Spring JDBC和H2依赖时,会自动配置JDBCTemplate Bean 和H2 DataSource,无需我们手动创建。
程序清单ContactRepositor从数据库存取contact.
package contacts;
import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
@Repository
public class ContactRepository {
private JdbcTemplate jdbc;
@Autowired
public ContactRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
public List<Contact> findAll() {
return jdbc.query(
"select id, firstName, lastName, phoneNumber, emailAddress " +
"from contacts order by lastName",
new RowMapper<Contact>() {
public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
Contact contact = new Contact();
contact.setId(rs.getLong(1));
contact.setFirstName(rs.getString(2));
contact.setLastName(rs.getString(3));
contact.setPhoneNumber(rs.getString(4));
contact.setEmailAddress(rs.getString(5));
return contact;
}
}
);
}
public void save(Contact contact) {
jdbc.update(
"insert into contacts " +
"(firstName, lastName, phoneNumber, emailAddress) " +
"values (?, ?, ?, ?)",
contact.getFirstName(), contact.getLastName(),
contact.getPhoneNumber(), contact.getEmailAddress());
}
}
7.尝试运行
Spring Boot 借助Starter依赖 和 自动配置特性,消除了Spring 应用构建过程绝大部分或全部配置,示例contact基本消除了Spring所有配置,仅在启动类添加了@CompomentScan启动组件扫描和@EnableAutoConfiguration启用Spring Boot 自动配置功能。
程序清单为实力启动类
package contacts;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Spring Boot 本身不知道自动配置任何信息,需要借助如上的特殊类来启动应用。
应用启动结果:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.1.4.RELEASE)
2018-01-05 10:40:55.758 INFO 16124 --- [ main] contacts.Application : Starting Application on LAPTOP-NFNPUROK with PID 16124 (started by user in E:\工作文档\资料\SpringiA4_SourceCode\Chapter_21\contacts)
2018-01-05 10:40:55.790 INFO 16124 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4e4aea35: startup date [Fri Jan 05 10:40:55 CST 2018]; root of context hierarchy
2018-01-05 10:40:56.210 INFO 16124 --- [ 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]]
2018-01-05 10:40:56.690 INFO 16124 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$5168bbab] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-01-05 10:40:56.709 INFO 16124 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionAttributeSource' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-01-05 10:40:56.717 INFO 16124 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionInterceptor' of type [class org.springframework.transaction.interceptor.TransactionInterceptor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-01-05 10:40:56.721 INFO 16124 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-01-05 10:40:57.426 INFO 16124 --- [ main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2018-01-05 10:40:57.645 INFO 16124 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2018-01-05 10:40:57.647 INFO 16124 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.54
2018-01-05 10:40:57.783 INFO 16124 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-01-05 10:40:57.784 INFO 16124 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1997 ms
2018-01-05 10:40:58.420 INFO 16124 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-01-05 10:40:58.423 INFO 16124 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-01-05 10:40:58.929 INFO 16124 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from URL [file:/E:/%e5%b7%a5%e4%bd%9c%e6%96%87%e6%a1%a3/%e8%b5%84%e6%96%99/SpringiA4_SourceCode/Chapter_21/contacts/target/classes/schema.sql]
2018-01-05 10:40:58.937 INFO 16124 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from URL [file:/E:/%e5%b7%a5%e4%bd%9c%e6%96%87%e6%a1%a3/%e8%b5%84%e6%96%99/SpringiA4_SourceCode/Chapter_21/contacts/target/classes/schema.sql] in 8 ms.
2018-01-05 10:40:59.048 INFO 16124 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-05 10:40:59.233 INFO 16124 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String contacts.ContactController.submit(contacts.Contact)
2018-01-05 10:40:59.234 INFO 16124 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String contacts.ContactController.home(java.util.Map<java.lang.String, java.lang.Object>)
2018-01-05 10:40:59.236 INFO 16124 --- [ 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)
2018-01-05 10:40:59.237 INFO 16124 --- [ 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)
2018-01-05 10:40:59.260 INFO 16124 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-05 10:40:59.261 INFO 16124 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-05 10:40:59.751 INFO 16124 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-01-05 10:40:59.845 INFO 16124 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080/http
2018-01-05 10:40:59.846 INFO 16124 --- [ main] contacts.Application : Started Application in 4.491 seconds (JVM running for 4.961)
应用启动成功我们便可访问应用,下图为应用运行结果