知识点梳理
课堂讲义
02-SpringBoot概述
SpringBoot提供了一种快速使用Spring的方式,基于约定优于配置的思想,可以让开发人员不必在配置与逻辑业务之间进行思维的切换,全身心的投入到业务逻辑的代码编写中,从而大大提高开发的效率。
约定优于配置:这是一种思想,即Springboot 框架开发人员的一种想法思想,springboot 的开发人员认为很多的配置在框架内部写死,比程序员自己灵活配置更好,基于这种思想,springboot 内部默认配置了很多默认值,我们无需配置即可使用(当然也可以配置)
官网:https://spring.io/projects/spring-boot
SpringBoot功能
1) 自动配置
Spring Boot的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定Spring配置应该用哪个,不该用哪个。该过程是SpringBoot自动完成的。
2) 起步依赖
起步依赖本质上是一个Maven项目对象模型(Project Object Model,POM),定义了对其他库的传递依赖,这些东西加在一起即支持某项功能。
简单的说,起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能。
3) 辅助功能
提供了一些大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等。
注意:Spring Boot 并不是对 Spring和SpringMVC 功能上的增强,而是提供了一种快速使用 Spring 的方式。
03-SpringBoot快速入门
需求:搭建SpringBoot工程,定义HelloController.hello()方法,返回”Hello SpringBoot!”。
使用版本:2.1.8.RELEASE
实现步骤:
①创建Maven项目
②导入SpringBoot起步依赖
<!--springboot工程需要继承的父工程--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.8.RELEASE</version> </parent> <dependencies> <!--web开发的起步依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
③定义Controller: 新建包package com.itheima.controller
package com.itheima.controller; @RestController public class HelloController { @RequestMapping("/hello") public String hello(){ return " hello Spring Boot !"; } }
④编写引导类:
package com.itheima; /** * 引导类。 SpringBoot项目的入口 */ @SpringBootApplication public class HelloApplication { public static void main(String[] args) { SpringApplication.run(HelloApplication.class,args); } }
易错点:
@SpringBootApplication默认只扫描HelloApplication类所在的包:com.itheima
//手动指定需要扫描的包路径
@SpringBootApplication(scanBasePackages = "com.itheima") //scanBasePackages="com.itheima" == <context:component-scan basePackages="com.itheima" />
⑤启动测试:SpringBoot 内置了tomcat
04-快速构建SpringBoot工程(了解)
注意:
1)这种方式创建需要连接网络
注意:
1.Spring提供快速创建模版:https://start.spring.io/
2.自动生成的项目中有一个插件,该插件的作用是打包时将所需要的的jar包都打包
<!-- 自动生成的项目中有一个插件,该插件的作用是打包时将所需要的的jar包都打包 -->
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
05-SpringBoot起步依赖原理分析
-
在spring-boot-starter-parent的父工程spring-boot-dependencies中定义了各种技术的版本信息,组合了一套最优搭配的技术版本。
-
在各种starter中,定义了完成该功能需要的坐标合集,其中大部分版本信息来自于父工程。
-
我们的工程继承parent,引入starter后不用写version,通过依赖传递就可以简单方便获得需要的jar包
<dependencies> <!--web开发的起步依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
06-SpringBoot配置-配置文件分类
SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用application.properties或者application.yml(application.yaml)进行配置。(htm->html)
-
默认配置文件名称:application
-
(了解)在同一级目录下优先级为:properties>yml > yaml(不同的版本优先级会有不同),最好不要同时使用多个格式的配置文件。
properties:
#配置内置Tomcat的端口
server.port=8080
yml:
server:
port: 8080
yml优势:减少编写重复配置项
properties格式
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db
jdbc.username=root
jdbc.password=itheima
yml格式
jdbc:
driver: com.mysql.jdbc.Driver
password: itheima
url: jdbc:mysql://localhost:3306/ssm_db
username: root
07-SpringBoot配置-yaml基本语法
-
大小写敏感,区分大小写
-
数据值前边必须有空格,作为分隔符
-
使用缩进表示层级关系
-
缩进时不允许使用Tab键,只允许使用空格(各个系统 Tab对应的 空格数目可能不同,导致层次混乱)。
-
缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
-
''#" 表示注释,从这个字符一直到行尾,都会被解析器忽略。
server:
port: 8080 #访问端口
address: 127.0.0.1
name: abc
08-SpringBoot配置-yaml数据格式
对象(map):键值对的集合。
#常用方式
person:
name: zhangsan
age: 30
#行内写法:不直观,不建议使用
person: {name: zhangsan}
数组:一组按次序排列的值
#常用方式
address:
- beijing
- shanghai
- zhengzhou
#行内写法:不直观,不建议使用
address: [beijing,shanghai]
纯量:单个的、不可再分的值
msg1: 'hello \n world' # 单引忽略转义字符
msg2: "hello \n world" # 双引识别转义字符
msg: test
单引号,双引号,和不加引号的区别
yaml中 字符串默认是无需加引号的 但是 如果有 特殊字符,比如 : 等 就需要加引号 单引号会原样输出, 双引号会识别转义符 比如 \n ,输出时会换行
参数引用
name: lisi
person:
name: ${name} # 引用上边定义的name值
09-SpringBoot配置-获取数据_1
使用@Value获取:
//获取普通配置
@Value("${name}")
private String name;
//获取对象属性
@Value("${person.name}")
private String name2;
//获取数组
@Value("${address[0]}")
private String address1;
//获取纯量
@Value("${msg1}")
private String msg1;
@RequestMapping("/hello2")
public String hello2() {
System.out.println(name);
System.out.println(name2);
System.out.println(age);
System.out.println(address1);
System.out.println(msg1);
System.out.println(msg2);
}
Environment(了解)
@Autowired
private Environment env;
@RequestMapping("/hello2")
public String hello2() {
System.out.println(env.getProperty("person.name"));
System.out.println(env.getProperty("address[0]"));
}
10-SpringBoot配置-获取数据_2
使用 @Component + @ConfigurationProperties组合注解读取对象的属性
person:
name: zhangsan
age: 20
address:
- anyang
- nanyang
注意:prefix一定要写
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private int age;
private String[] address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getAddress() {
return address;
}
public void setAddress(String[] address) {
this.address = address;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
HelloController
@RestController
public class HelloController {
@Autowired
private Person person;
@RequestMapping("/hello2")
public String hello2() {
System.out.println(person);
String[] address = person.getAddress();
System.out.println("addressArray: " + Arrays.toString(address));
return "hello Spring Boot 222!";
}
}
如果先把Person配置类写好后,引入如下坐标:在application编写具体属性值时会有提示
<!--解决提示问题:引入后,有时需重启idea才有提示--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
11-SpringBoot配置-profile(了解)
-
profile是用来完成不同环境下,配置动态切换功能的。
-
profile配置方式
-
多profile文件方式:提供多个配置文件,每个代表一种环境。
-
application-dev.properties/yml 开发环境
application-test.properties/yml 测试环境
application-pro.properties/yml 生产环境
-
yml多文档方式(不建议使用):在yml中使用 --- 分隔不同配置
#指定使用的配置环境为dev spring: profiles: active: dev --- server: port: 8081 spring: profiles: dev --- server: port: 8082 spring: profiles: test --- server: port: 8083 spring: profiles: pro ---
-
profile激活方式
-
配置文件(application): spring.profiles.active=dev(开发使用)
-
虚拟机参数:在VM options 指定:-Dspring.profiles.active=dev
-
命令行参数:java –jar xxx.jar --spring.profiles.active=dev(运维使用)
通过 spring.profiles.active 指定的参数比默认的配置优先级高
12-SpringBoot配置-项目内部配置文件加载顺序(了解)
加载顺序为上文的排列顺序,高优先级配置的属性会生效
-
file:./config/:当前项目下的/config目录下
-
file:./ :当前项目的根目录
-
classpath:/config/:classpath的/config目录
-
classpath:/ :classpath的根目录
加载顺序为上文文的排列顺序,高优先级配置的属性会生效
外部文件夹config>外部根目录文件>项目内config文件夹>项目内根目录
13-SpringBoot配置-项目外部配置加载顺序
外部配置文件的使用是为了能对jar 内部已经配好的东西,运行时再次修改
1.命令行
java -jar app.jar --name="Spring“ --server.port=9000
2.指定配置文件位置
java -jar myproject.jar --spring.config.location=e://application.properties
3.外部不带profile的properties文件
classpath:/config/application.properties
classpath:/application.properties
命令行优先级> 外部conf/properties文件> 外部properties文件
相同的配置 优先级如下(由高到底): 1)命令行直接指定参数方式 2)命令行指定文件名称 3)外部config文件夹 4)外部根目录下的文件 5)内部config 文件夹下的资源 6)内部 根路径下的文件 1 >2>3>4>5>6 即1 的优先级最高
14-SpringBoot整合Junit
-
搭建SpringBoot工程
-
引入starter-test起步依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
-
编写测试类
通过@SpringBootTest(classes = SpringbootJunitApplication.class)指定项目引导类
/** * 测试类 */ @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringbootJunitApplication.class) public class UserServiceTest { @Autowired UserService userService; @Test public void test(){ userService.add(); } }
-
执行单元测试
15-SpringBoot整合mybatis(重点)
15.1 准备工作
创建数据库springboot和表t_user
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */;
USE `springboot`;
/*Table structure for table `t_user` */
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`password` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*Data for the table `t_user` */
insert into `t_user`(`id`,`username`,`password`) values (1,'zhangsan','123'),(2,'lisi','234');
COMMIT;
15.2 整合工作
①搭建SpringBoot工程
②引入mybatis起步依赖,添加mysql驱动
<dependencies> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
③编写DataSource和MyBatis相关配置:application.yml
# datasource
spring:
datasource:
url: jdbc:mysql:///springboot?serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
④定义表和实体类
public class User { private int id; private String username; private String password; //添加set,get方法 }
⑤编写dao
-
第一种方式:纯注解开发
@Mapper @Repository public interface UserMapper { @Select("select * from t_user") public List<User> findAll(); }
-
第二种方式:xml配置:必须添加扫描配置(application.yml)
#纯注解不需要以下mybatis配置 mybatis: mapper-locations: classpath:mapper/*Mapper.xml # mapper映射文件路径 type-aliases-package: com.itheima.springbootmybatis.domain
使用xml配置文件配置SQL,并删除注解配置的sql语句:
mapper.xml
<?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.itheima.springbootmybatis.mapper.UserXmlMapper"> <select id="findAll" resultType="user"> select * from t_user </select> </mapper> @Mapper @Repository public interface UserXmlMapper { public List<User> findAll(); }
⑥编写SpringBoot引导类
注意事项:MyBatis扫描mapper默认为当前引导类所在的包;如果mapper或dao所在的包既不是引导类所在的包也不是子包,则必须使用@MapperScan("com.ithteima.dao")
package com.itheima.springbootmybatis; @SpringBootApplication //@MapperScan("com.itheima.springbootmybatis.mapper") public class SpringbootMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMybatisApplication.class, args); } }
⑦测试
@RunWith(SpringRunner.class) @SpringBootTest public class SpringbootMybatisApplicationTests { @Autowired private UserMapper userMapper; @Autowired private UserXmlMapper userXmlMapper; @Test public void testFindAll() { List<User> list = userMapper.findAll(); System.out.println(list); } @Test public void testFindAll2() { List<User> list = userXmlMapper.findAll(); System.out.println(list); } }
16-SpringBoot整合redis
①搭建SpringBoot工程
②引入redis起步依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
③配置redis相关属性
spring:
redis:
host: 127.0.0.1 # redis的主机ip
port: 6379
④编写测试方法,执行单元测试
@RunWith(SpringRunner.class) @SpringBootTest public class SpringbootRedisApplicationTests { @Autowired private RedisTemplate redisTemplate; @Test public void testSet() { //存入数据 redisTemplate.boundValueOps("name").set("zhangsan"); } @Test public void testGet() { //获取数据 Object name = redisTemplate.boundValueOps("name").get(); System.out.println(name); } }
扩展部分
spring boot 整合webmvc 后 我们可以调整日志的输入级别
application.yml
# spring boot 中输入日志
logging:
level:
# com.itheima 的日志级别为 debug
com.itheima: debug
# org.springframework 的日志级别为 info
org.springframework: info
UserController
@RestController public class UserController { Logger logger = LoggerFactory.getLogger(UserController.class); @RequestMapping("/hello") public String hello(){ logger.debug("debug"); logger.info("info"); logger.warn("warn"); return "hello"; } }
2) lombok
项目中大量每个类都需要使用 对象, 同时我们的 pojo 类中需要 大量的固定的get,set,toString 方法
lombok 插件能够简化我们的代码
使用方式
1) 首先安装idea 插件:lombok
idea->Settings->Plugins->Marketplace->搜索Lombok下载后重启idea
2) 在项目中导入坐标
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
3) 使用
然后可以在Bean上使用:
@Data :自动提供getter和setter、hashCode、equals、toString等方法
@Getter:自动提供getter方法
@Setter:自动提供setter方法
@Builder:User.builder().id(30).name("lisi").build();
@AllArgsConstructor:生成构造方法
@Slf4j:自动在bean中提供log变量,其实用的是slf4j的日志功能。
@RestController @Slf4j public class UserController { @RequestMapping("/hello") public String hello(){ log.debug("debug"); log.info("info"); log.warn("warn"); return "hello"; } }
@Data public class User { private int id; private String username; private String password; }
3) 热加载
一般来说,项目源码修改后需要重启Tomcat服务器才能生效。SpringBoot提供了不重启生效的方法:
-
添加热加载坐标
<!--热加载--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>
-
修改源码后,点击idea菜单栏Build->Recompile 'Xxxx.java'
-
刷新浏览器,即可看到修改后的内容
© 著作权归作者所有
发表评论