Spring Boot简介
Spring应用需要大量的配置,各种XML配置、注解配置让人眼花缭乱。为了简化Spring应用的构建和开发过程,Pivotal团队提供了一个基于Spring的新开源框架,这就是Spring Boot。
SpringBoot是基于SpringMVC构建的新一代Web开发框架。与SpringMVC相比,SpringBoot的配置更加简单。
pom中添加对SpringBoot的依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
</parent>
<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>
</dependency>
<!-- ... -->
</dependencies>
Spring Boot 提供了大量开箱即用(out-of-the-box)的依赖模块,例如 spring-boot-starter-redis、spring-boot-starter-data-mongodb 和 spring-boot-starter-data-elasticsearch
等。这些依赖模块为 Spring Boot 应用提供了大量的自动配置,使得 Spring Boot 应用只需要非常少量的配置甚至零配置,便可以运行起来,更多的精力专注于业务逻辑的开发。春季启动启动器
Spring Boot应用
创建一个新的SpringBoot应用程序:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
//或者
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
private static Class<Application> applicationClass = Application.class;
}
MVC部分与Spring MVC一致:
@Controller
@RequestMapping("/test")
public class TestCtrl {
@GetMapping("/hello")
@ResponseBody
public String Hello(){
return "<h5>Hello Spring Boot</h5>";
}
}
Spring Boot内置了servlet容器和Tomcat服务器,并且默认配置了Servlet。可以直接启动主任务程序:
spring boot默认的上下文是/
不是项目名,直接输入接口映射访问。
SpringBoot内置了一个Tomcat服务器,它也是一个内置的Servlet容器。因此,直接运行项目就可以看到效果。不需要额外的部署或者Servlet相关的配置。同时SpringBoot也会帮我们做很多配置工作。通过@SpringBootApplication注解,它会帮助我们开启@EnableWebMvc和@ComponentScan功能,这意味着SpringBoot和SpringMvc会寻找同一个包下的@Controller、@Configuration等类进行自动配置。
Spring Boot配置文件
得益于 Spring Boot 的启动器机制,Spring Boot 无需导入各种依赖项并配置各种 XML 配置文件。
数据库驱动所需参数,或服务参数都将在这些配置文件配配置。
YAML/YML/PROPERTIES
application.properties/yml/yaml
是默认配置spring boot参数的,会被自动识别。
name: abc
# 对象
person:
name: zhangsan
age: 20
# 对象的行内写法
person1: {
name: laowang,age: 20}
#数组
address:
- beijing
- shanghai
#数组行内写法
address1: [wuhan,hangzhou]
#变量
message1: 'hello \n world' #原样输出
message2: "hello \n world" #识别含义字符
#引用参数
description: ${
message1}
获取配置参数
读取配置内容:
@Value注解
该注解读取配置文件定义的属性值,也可读取IoC容器的bean的属性,方法支持SpEl表达式。
Environment对象(配置文件对象)
//由于spring boot默认读取application.properties文件所以不用注解导入
@RestController
@RequestMapping("/print")
public class Test1Ctrl {
@Value("${name}") private String name; //字符串注入
@Value("${address[0]}") private String address; //数组注入
@Value("${person.name}") private String person; //注入对象属性
@Autowired
private Environment environment; //springboot默认读取的文件装配到配置文件对象
@GetMapping("/name")
public String printName(){
return name;
}
@GetMapping("/list")
protected String printList(){
return address;
}
@GetMapping("/person")
public String printPerson(){
return person;
}
@GetMapping("/environment")
public String printEnvironment(){
return environment.getProperty("description");
}
}
@ConfigurationProperties
将配置文件映射为一个配置类,在自动装配来获取值。
//Student.java:
@Component //将该类注入到IoC容器
@ConfigurationProperties(prefix = "student") //该注解实现了将配置文件映射为一个类,prefix绑定配置类的其中一个对象
public class Student {
private String name;
private String id;
}
//application.yaml
student:
name: lihua
id: s001
//controller
@RestController
@RequestMapping("/property")
public class Test2Ctrl {
@Resource
private Student student; //注意将Student类注入IoC容器并通过@ConfigurationProperties注解将配置文件映射为一个bean
@GetMapping("/student")
protected Student printStudent(){
return student;
}
}
profile
开发Spring boot时,会在不同的环境中安装一组程序,例如开发环境、测试环境、生产环境。数据库地址、服务器端口等配置不同。每次打包的时候都要修改配置文件,非常麻烦。 Profile 该功能用于动态配置切换。
- 配置文件配置方法
-
多profile文件方式
在主配置文件中设置激活的配置文件,该文件就会生效。 -
yml多文档模式
通过---
分割不同工作区。
- 配置文件激活方法
- 配置文件
上述配置文件中的active属性等于谁就启动。
-
虚拟机命令
-
命令行参数
Spring boot可以打成jar包通过java -jar [jar包路径]
即可运行项目,在该命令后配置启动参数文件java -jar [jar包路径] --spring.profiles.active=pro
即可启动active=pro的配置。
配置文件加载顺序
每个配置文件都会加载,重复的优先级高的生效。除了内部配置文件的配置,也可以通过命令行实现外部文件的配置,在运行jar包时,配置响应的参数,或直接新的配置文件的位置来覆盖内部配置。
静态资源默认读取目录
Spring boot整合其他框架
- 单元测试
引入starter-test
依赖;在测试类上添加注解、@RunWith(SpringRunner.class)和@SpringBootTest(class=启动类.class)
。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDemoApplication.class)
public class UserTest {
@Autowired
private UserService userService;
@Test
public void addTest(){
userService.userAdd();
}
}
//别忘了将测试类注入IoC容器
@Service
public class UserService {
public void userAdd(){
System.out.println("add...");
}
}
- 整合Redis
导入Redis依赖,配置redis,注入RedisTemplates模板
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<scope>test</scope>
</dependency>
spring:
redis:
host: 127.0.0.1
port: 6379
@Autowired
private RedisTemplate redisTemplate;
public void redisTest(){
redisTemplate.boundValuesOps("name").set("zhangsan");
Object name=redisTemplate.boundValuesOps("name").get();
System.out.println(name);
}
- 集成mybatis
引入mybatis依赖和数据库驱动;编写DataSource和myabtis的相关配置,定义所需的实体类来实现dao和mapper注解,或者开发配置文件。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
Mybatis可以用于注解开发或者配置文件开发。方法如下:
注释开发
- yml数据源配置
Spring Boot的默认应用程序配置文件提供了数据源配置。如果按照规定的语法写的话,是可以被spring识别的。当然,你也可以导入druid连接池,然后配置datasource数据源。
#datasource配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/[数据名]?characterEncoding=utf-8
password: ...
username: ...
- @Mapper注解替换xml配置文件
从mybatis3.4.0开始加入了@Mapper注解,代替xml配置文件,实现完全注解开发,在普通项目中我们需要读取xml配置文件,构建SqlSessionFactory和SqlSession获取Mapper类,再调用方法。而@Mapper注解集成了这些功能,无需配置。注解在一个Mapper映射类上,就能完成SqlSessionFactory和SqlSession的创建,并调用getMapper()
方法返回一个Mapper类。
spring也提供了@MapperScan
是org.mybatis.spring的注解共差不多。
- 编写 POJO
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
- 编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDemoApplication.class)
public class UserTest {
//数据库测试变量
@Autowired
private UserMapper userMapper;
@Test
public void selectAll(){
List<User> list= userMapper.selectAll();
System.out.println(list);
}
}
//spring自动创建SqlSession调用getMapper()方法
- mybatis for spring boot的XML配置开发
ssm项目中xml配置文件路径和mapper映射路径都是需要配置的并注入IoC容器的,spring boot由默认的配置,有的需要覆盖成自己的在指定位置覆盖生效application
。ssm环境设置
- application文件中对mybatis的默认配置进行覆盖。(
mybatis-spring-boot-starter
导入时就有默认配置了)
# datasource
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8
password: ...
username: ...
# mybatis配置
mybatis:
config-location: #指定mybatis核心配置文件,用默认配置即可
mapper-locations: classpath:mapper/*Mapper.xml #mapper.xml映射路径
type-aliases-package: com.example.springbootdemo.model #配置resultType等类型的全限定名,然后resultType=类名即可
映射路径需要覆盖默认配置。
- 编写mapper.xml配置文件和map映射器类
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.springbootdemo.dao.UserMapper">
<select id="selectAll" resultType="com.example.springbootdemo.model.User">
<!-- type-aliases-package进行了配置这里可以直接写User-->
select * from user
</select>
</mapper>
如果没配置type-aliases-package
又没写全就会出现这样的错误:
@Repository
@Mapper
public interface UserMapper {
//@Select("select * from user")
List<User> selectAll();
}
- POJO与上面的User相同,测试类如下
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDemoApplication.class)
public class UserTest {
//数据库测试变量
@Autowired
private UserMapper userMapper;
@Test
public void selectAll(){
List<User> list= userMapper.selectAll();
System.out.println(list);
}
由此可以看出,注解开发比配置文件开发更简单,少了一个@Select,@Insert…的注解,却多了mybatis的覆盖配置参数,mapper.xml文件,mapper接口,其他都一样。除了很难的sql语句建议注解开发。
Spring Boot自动配置
Spring Boot的最大的特点就是简化了各种xml配置内容,省去了SSM框架各种xml配置,如:数据源、连接池、会话工厂、事务管理等。spring实现完全注解开发,Spring Boot就是全用注解来对一些常规的配置做默认配置,简化xml配置内容,使你的项目能够快速运行。
感谢作者@木竹子
感谢作者@
感谢作者@Java3y
感谢以上作者虽然我还看不懂 -。
@Enable*注解
Spring Boot注解提供了提供了很多该注解盖头的注解,用于开启某些功能,底层时使用@Import注解到日一些配置类,实现bean的动态加载。
@Enable注解导入的依赖于@Import注解的类会被spring、@Enable加载到IoC容器中注解导入@Import注解。
@EnableAutoConfiguration注解
该注解内部使用@Inport(AutoConfiggurationImportSelector.class)来加载类。
配置问津位置:META-INF/spring.factories,该注解定义了大量配置类,当spring启动时,会加载这些配置类,初始化bean。
Spring Boot切换内置web服务器
spring boot的web环境默认使用Tomcat服务器,但Spring boot内置了四种服务器可供选择:jetty
,
netty
,tomcat
,undertow
。
<!--将tomcat排除-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<executions>
<exclusions>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusions>
</executions>
<dependency>
<!--引入新的服务器依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
<scope>test</scope>
</dependency>
Spring Boot事件监听
spring监听机制是对java提供的监听机制的封装。 java事件的监听机制有以下几类:
- Event:继承java.util.EventObject类的对象
- 事件源Source:任意Object对象
- Listener监听器:实现java.util.EventListenter接口的对象
春季启动监听器:
- 应用程序上下文初始化器
- SpringApplicationRunListener
从上到下依次是:项目启动中,环境开始准备,环境准备完毕,上下文开始加载,上下文加载完成,项目启动完成,项目启动失败的项目声明周期函数
。
上面要生效需要配置,再spring boot项目中的resources目录下创建MATA-INF/spring.factores
并配置:
org.springframework.contex.ApplicationContextInitializer=exanple.text.listenerMyApplicationContextInitializer
//前面是监听器,后面是自定义的实现类
//注意都要写全限定名
//SpringApplicationRunListener的配置一样,再实现类重写方法实现监听
//SpringApplicationRunListener需要重写有参构造方法,参数为事件源和agrs的String数组
- CommandLineRunner
接口偶一个run方法,当项目启动后执行run方法。 - ApplicationRunner
接口偶一个run方法,当项目启动后执行run方法。
Spring Boot监控
Spring Boot自带监控功能,可以监控程序内部运行状态,如bean加载状态、配置属性、日志信息等。
- 导入相关坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<scope>test</scope>
</dependency>
- 启动程序并访问http://localhost:8080/actuator
模板引擎
在java领域,表现层技术主要有四种:jsp
、freemarker
、velocity
、Thymeleaf
。
对于传统jsp或者其他模板来说,没有一个模板引擎的后缀为.html,就拿jsp来说jsp的后缀为.jsp,它的本质就是在一个html文件java语法、标签然后执行时候通过后台的jre重新编译这个文件最终返回一个html页面,离不开服务端,浏览器端是无法直接识别.jsp文件。
执行过程中依赖于服务端的jre
:
JSP模板引擎
Spring Boot项目部署
spring boot项目支持两种部署到服务器的方式
- jar包
用IDE打成jar包,再上传到服务器,再同一目录下java -jar [jar包]
- 战争包
在pom中修改打包方式<packaging>war</packaging>
,主程序继承SpringBootServletInitializer
并重写一个方法:
@SpringBootApplication
public class SpringbootupdateApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringbootupdateApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringbootupdateApplication.class);
}
}
可以在<build>
标签中用指定打包名称:
<build>
<finalName>${filename}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
打包后,直接将war文件放入tomcat中即可,上下文连接就成为war包的名称。