Spring Boot
Spring Boot介绍
什么是Spring Boot
Spring Boot是一个框架,一种全新的编程规范,它的产生简化了框架的使用,所谓的简化是指简化了Spring众多框架中所需的大量且繁琐的配置文件,所以Spring Boot是一个服务于框架的框架,服务范围是简化配置文件,所以从本质上来说,Spring Boot其实就是Spring框架的另一种表现形式。
Spring Boot特征
- 使用Spring Boot可以创建独立的Spring应用程序
- 在Spring Boot中直接嵌入了Tomcat、Jetty、Undertow等Web容器,所以在使用Spring Boot做Web开发时不需要部署WAR文件
- 通过提供自己的启动器(Starter)依赖,简化项目构建配置
- 尽量的自动配置Spring和第三方库
- 提供了生产就绪特征,如:度量指标,运行状况检查和外部化配置
- 绝对没有代码生成,不需要XML配置文件
Spring Boot版本介绍
- SNAPSHOT:快照版,即开发版
- CURRENT:最新版,但是不一定是稳定版
- GA:General Availability,正式发布的版本
创建基于Spring Boot的项目
- 通过官网创建项目
- 通过 IDEA 的脚手架工具创建
- 通过 IDEA 的 Maven 项目创建
修改 POM 文件
<?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.bjsxt</groupId>
<artifactId>springbootdemo3</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Spring Boot 项目结构介绍
POM 文件
继承
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
Spring Boot 的父级依赖,只有继承它项目才是 Spring Boot 项目。 spring-boot-starter-parent 是一个特殊的 starter,它用来提供相关的 Maven 默认依赖。使 用它之后,常用的包依赖可以省去 version 标签。
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
启动器依赖
插件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
spring-boot-maven-plugin 插件是将 springboot 的应用程序打包成 jar 包的插件。将所有 应用启动运行所需要的 jar 包都包含进来,从逻辑上将具备了独立运行的条件。当运行"mvn package"进行打包后,使用"java -jar"命令就可以直接运行。
启动类
Spring Boot的启动类的作用是启动Spring Boot项目,是基于Main方法来运行的。
注意:启动类在启动时会做注解扫描(@Controller、@Service、@Repository…),扫描位置为同包或者子包下的注解,所以启动类的位置应放于包的根下。
启动类与启动器区别
- 启动类表示项目的启动入口
- 启动器表示jar包的坐标
创建启动类
/**
* Spring Boot 启动类
*/
@SpringBootApplication
public class SpringBootDemo3Application {
public static void main(String[] args){
SpringApplication.run(SpringBootDemo3Application.class,args);
}
}
启动器
Spring Boot将所有的功能场景都抽取出来,做成一个个的starter(启动器),只需要在项目里面引入这些starter,相关场景的所有依赖都会导入进来,要用什么功能就导入什么场景,在jar包管理上非常方便,最终实现一站式开发。
Spring Boot提供了多达44个启动器。
spring-boot-starter
这是Spring Boot的核心启动器,包含了自动配置、日志和YAML。
spring-boot-starter-actuator
帮助监控和管理应用。
spring-boot-starter-web
支持全栈式Web开发,包括Tomcat和spring-webmvc。
spring-boot-starter-amqp
通过spring-rabbit来支持AMQP协议(Advanced Message Queuing Protocol)。
spring-boot-starter-aop
支持面向方面的编程即AOP,包括spring-aop和AspectJ。
spring-boot-starter-artemis
通过Apache Artemis支持JMS的API(Java Message Service API)。
spring-boot-starter-batch
支持Spring Batch,包括HSQLDB数据库。
spring-boot-starter-cache
支持Spring的Cache抽象。
spring-boot-starter-cloud-connectors
支持Spring Cloud Connectors,简化了在像Cloud Foundry或Heroku这样的云平台上连接服务。
spring-boot-starter-data-elasticsearch
支持ElasticSearch搜索和分析引擎,包括spring-data-elasticsearch。
spring-boot-starter-data-gemfire
支持GemFire分布式数据存储,包括spring-data-gemfire。
spring-boot-starter-data-jpa
支持JPA(Java Persistence API,包括spring-data-jpa、spring-orm、hibernate。
spring-boot-starter-data-MongoDB
支持MongoDB数据,包括spring-data-mongodb。
spring-boot-starter-data-rest
通过spring-data-rest-webmvc,支持通过REST暴露Spring Data数据仓库。
spring-boot-starter-data-solr
支持Apache Solr搜索平台,包括spring-data-solr。
spring-boot-starter-freemarker
支持FreeMarker模板引擎。
spring-boot-starter-groovy-templates
支持Groovy模板引擎。
spring-boot-starter-hateoas
通过spring-hateoas支持基于HATEOAS的RESTful Web服务。
spring-boot-starter-hornetq
通过HornetQ支持JMS。
spring-boot-starter-integration
支持通用的spring-integration模块。
spring-boot-starter-jdbc
支持JDBC数据库。
spring-boot-starter-jersey
支持Jersey RESTful Web服务框架。
spring-boot-starter-jta-atomikos
通过Atomikos支持JTA分布式事务处理。
spring-boot-starter-jta-bitronix
通过Bitronix支持JTA分布式事务处理。
spring-boot-starter-mail
支持javax.mail模块。
spring-boot-starter-mobile
支持spring-mobile。
spring-boot-starter-mustache
支持Mustache模板引擎。
spring-boot-starter-Redis
支持Redis键值存储数据库,包括spring-redis。
spring-boot-starter-security
支持spring-security。
spring-boot-starter-social-facebook
支持spring-social-facebook
spring-boot-starter-social-linkedin
支持pring-social-linkedin
spring-boot-starter-social-twitter
支持pring-social-twitter
spring-boot-starter-test
支持常规的测试依赖,包括JUnit、Hamcrest、Mockito以及spring-test模块。
spring-boot-starter-thymeleaf
支持Thymeleaf模板引擎,包括与Spring的集成。
spring-boot-starter-velocity
支持Velocity模板引擎。
spring-boot-starter-websocket
支持WebSocket开发。
spring-boot-starter-ws
支持Spring Web Services。
spring-boot-starter-remote-shell
增加了远程ssh shell的支持。
spring-boot-starter-actuator
增加了面向产品上线相关的功能,比如测量和监控。
spring-boot-starter-jetty
引入了Jetty HTTP引擎(用于替换Tomcat)。
spring-boot-starter-log4j
支持Log4J日志框架。
spring-boot-starter-logging
引入了Spring Boot默认的日志框架Logback。
spring-boot-starter-tomcat
引入了Spring Boot默认的HTTP引擎Tomcat。
spring-boot-starter-undertow
引入了Undertow HTTP引擎(用于替换Tomcat)。
配置文件
Spring Boot提供一个名称为application的全局配置文件,支持两种格式:properties格式和YAML格式。
Properties格式
配置Tomcat监听端口
server.port=8888
YAML格式
YAML格式配置文件的扩展名可以是yaml或者yml。
基本格式要求
- 大小写敏感
- 使用缩进代表层级关系
- 相同的部分只出现一次
配置Tomcat监听端口
server:
port: 8888
配置文件存放位置
- 当前项目根目录中
- 当前项目根目录下的一个/config子目录中
- 项目的resources即classpath根路径中
- 项目的resources即classpath根路径下的/config目录中
配置文件加载顺序
不同格式的加载顺序
如果同一个目录下 ,有 application.yml 也 有 application.properties , 默 认 先 读 取 application.properties。
如果同一个配置属性,在多个配置文件都配置了,默认使用第 1 个读取到的,后面读取 的不覆盖前面读取到的。
不同位置的加载顺序
- 当前项目根目录下的一个/config 子目录中(最高)
config/application.properties
config/application.yml - 当前项目根目录中(其次)
application.properties
application.yml - 项目的 resources 即 classpath 根路径下的/config 目录中(一般) resources/config/application.properties
resources/config/application.yml - 项目的 resources 即 classpath 根路径中(最后)
resources/application.properties
resources/application.yml
配置文件中的占位符
占位符语法
语法:${}
占位符作用
- "${}"中可以获取框架提供的方法中的值如:random.int 等。
- 占位符可以获取配置文件中的键的值赋给另一个键作为值。
生成随机数
- ${random.value} - 类似 uuid 的随机数,没有"-"连接
- ${random.int} - 随机取整型范围内的一个值
- ${random.long} - 随机取长整型范围内的一个值
- ${random.long(100,200)} - 随机生成长整型 100-200 范围内的一个值
- ${random.uuid} - 生成一个 uuid,有短杠连接
- ${random.int(10)} - 随机生成一个 10 以内的数
- ${random.int(100,200)} - 随机生成一个 100-200 范围以内的数
bootstrap 配置文件
bootstrap 配置文件介绍
Spring Boot 中有两种上下文对象,一种是 bootstrap, 另外一种是 application, bootstrap 是应用程序的父上下文,也就是说 bootstrap 加载优先于 applicaton。bootstrap 主要用于从 额外的资源来加载配置信息,还可以在本地外部配置文件中解密属性。这两个上下文共用一 个环境,它是任何 Spring 应用程序的外部属性的来源。bootstrap 里面的属性会优先加载, 它们默认也不能被本地相同配置覆盖。
bootstrap 配置文件特征
- boostrap 由父 ApplicationContext 加载,比 applicaton 优先加载。
- boostrap 里面的属性不能被覆盖。
bootstrap 与 application 的应用场景
application 配置文件主要用于 Spring Boot 项目的自动化配置。
bootstrap 配置文件有以下几个应用场景。
- 使用 Spring Cloud Config 配置中心时,这时需要在 bootstrap 配置文件中添加连 接到配置中心的配置属性来加载外部配置中心的配置信息。
- 一些固定的不能被覆盖的属性。
- 一些加密/解密的场景。
Spring Boot 的核心注解
@SpringBootApplication
是 SpringBoot 的启动类。
此注解等同于@Configuration+@EnableAutoConfiguration+@ComponentScan 的组合。
@SpringBootConfiguration
@SpringBootConfiguration 注解是@Configuration 注解的派生注解,跟@Configuration 注解的功能一致,标注这个类是一个配置类,只不过@SpringBootConfiguration 是 springboot 的注解,而@Configuration 是 spring 的注解 。
@Configuration
通过对 bean 对象的操作替代 spring 中 xml 文件
@EnableAutoConfiguration
Spring Boot 自动配置(auto-configuration):尝试根据你添加的 jar 依赖自动配置你的 Spring 应用。是@AutoConfigurationPackage 和@Import(AutoConfigurationImportSelector.class) 注解的组合。
@AutoConfigurationPackage
@AutoConfigurationPackage 注解,自动注入主类下所在包下所有的加了注解的类 (@Controller,@Service 等),以及配置类(@Configuration)
@Import({AutoConfigurationImportSelector.class})
直接导入普通的类
导入实现了 ImportSelector 接口的类
导入实现了 ImportBeanDefinitionRegistrar 接口的类
@ComponentScan
组件扫描,可自动发现和装配一些 Bean。
@ConfigurationPropertiesScan
@ConfigurationPropertiesScan 扫描配置属性。@EnableConfigurationProperties 注解的作 用是使用 @ConfigurationProperties 注解的类生效。
编写HelloWorld
- 创建项目
- 修改 POM 文件
<?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.bjsxt</groupId>
<artifactId>springboothelloworld</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.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>
</plugin>
</plugins>
</build>
</project>
- 修改 Tomcat 端口
server:
port: 8888
- 创建启动类
/**
* 启动类
*/
@SpringBootApplication
public class SpringBootHelloWorldApplication {
public static void main(String[] args){
SpringApplication.run(SpringBootHelloWorldApplication.class,args);
}
}
- 创建 Controller
/**
* 处理请求 Controller
*/
@RestController // @Controller+@ResponsBody 直接返回字符串
public class HelloWorldController {
@RequestMapping("/helloWorld")
public String showHelloWorld() {
return "HelloWorld";
}
}
Spring Boot 在 Controller 中常用注解
@RestController
@RestController 相当于@Controller+@ResponseBody 注解
如果使用@RestController 注解,Controller 中的方法无法返回页面,相当于在方法上面自动加了@ResponseBody注解,所以没办法跳转并传输数据到另一个页面,所以 InternalResourceViewResolver也不起作用,返回的内容就是Return里的内容。
@GetMapping
@GetMapping 注解是@RequestMapping(method = RequestMethod.GET)的缩写。
@PostMapping
@PostMapping 注解是@RequestMapping(method = RequestMethod.POST)的缩写。
@PutMapping
@PutMapping 注解是@RequestMapping(method = RequestMethod.PUT)的缩写。
@DeleteMapping
@DeleteMapping 注解是@RequestMapping(method = RequestMethod.DELETE)的缩写。
Spring Boot 整合 Web 层技术
整合 Servlet
整合 Servlet 方式一
通过注解扫描完成 Servlet 组件的注册
- 创建 Servlet
/**
* 整合 Servlet 方式一
*/
@WebServlet(name = "FirstServlet", urlPatterns = "/first")
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
System.out.println("First Servlet........");
}
}
- 修改启动类
@SpringBootApplication
@ServletComponentScan // 在spring Boot启动时会扫描@WebServlet 注解,并将该类实例化
public class SpringbootwebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootwebApplication.class, args);
}
}
整合 Servlet 方式二
通过方法完成 Servlet 组件的注册
- 创建 Servlet
/**
* 整合 Servlet 方式二
*/
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
System.out.println("Second Servlet........");
}
}
- 创建 Servlet 配置类
/**
* Servlet 配置类
*/
@Configuration
public class ServletConfig {
/**
* 完成 Servlet 组件的注册
*/
@Bean
public ServletRegistrationBean getServletRegistrationBean() {
ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
bean.addUrlMappings("/second");
return bean;
}
}
整合 Filter
整合 Filter 方式一
通过注解扫描完成 Filter 组件注册
- 创建 Filter
/**
* 整合 Filter 方式一
*/
//@WebFilter(filterName = "FirstFilter",urlPatterns = {"*.do","*.jsp"})
@WebFilter(filterName = "FirstFilter", urlPatterns = "/first")
public class FirstFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("进入 First Filter");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("离开 First Filter");
}
@Override
public void destroy() {
}
}
- 修改启动类
@SpringBootApplication
@ServletComponentScan // 在spring Boot启动时会扫描 @WebServlet,@WebFilter 注解,并将该类实例化
public class SpringbootwebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootwebApplication.class, args);
}
}
整合 Filter 方式二
通过方法完成 Filter 组件注册
- 创建 Filter
/**
* 整合 Filter 方式二
*/
public class SecondFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("进入 Second Filter");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("离开 Second Filter");
}
@Override
public void destroy() {
}
}
- 创建 Filter 配置类
/**
* Filter 配置类
*/
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean getFilterRegistrationBean(){
FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());
//bean.addUrlPatterns(new String[]{"*.do","*.jsp"});
bean.addUrlPatterns("/second"); return bean;
}
}
整合 Listener
整合 Listener 方式一
通过注解扫描完成 Listener 组件注册
- 编写 Listener
/**
* 整合 Listener
*/
@WebListener
public class FirstListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent event) {
}
public void contextInitialized(ServletContextEvent event) {
System.out.println("Listener ...Init......");
}
}
- 修改启动类
@SpringBootApplication
@ServletComponentScan//在spring Boot启动时会扫描@WebServlet,@WebFilter,@WebListener 注解,并将该类实例化
public class SpringbootwebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootwebApplication.class, args);
}
}
整合 Listener 方式二
通过方法完成 Listener 组件注册
- 编写 Listener
/**
* 整合 Listener 方式二
*/
public class SecondListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent event) {
}
public void contextInitialized(ServletContextEvent event) {
System.out.println("Second....Listener ...Init......");
}
}
- 创建 Listener 配置类
/**
* Listener 配置类
*/
@Configuration
public class ListenerConfig {
@Bean
public ServletListenerRegistrationBean getServletListenerRegistrationBean() {
ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new SecondListener());
return bean;
}
}
Spring Boot 访问静态资源
在 SpringBoot 项目中没有我们之前常规 web 开发的 WebContent(WebApp),它只有 src 目录。在 src/main/resources 下面有两个文件夹,static 和 templates。SpringBoot 默认在 static 目录中存放静态页面,而 templates 中放动态页面。
static目录
Spring Boot 通过 classpath/static 目录访问静态资源。注意存放静态资源的目录名称必须 是 static。
templates 目录
在Spring Boot 中不推荐使用 jsp 作为视图层技术,而是默认使用 Thymeleaf 来做动态页 面。Templates 目录这是存放 Thymeleaf 的页面。
静态资源存放其他位置
Spring Boot 访问静态资源的位置
classpath:/META‐INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
自定义静态资源位置
#配置静态资源访问路径
spring.resources.static-locations=classpath:/suibian/,cla sspath:/static/