SpringBoot:
约定大于配置
springboot简化了程序员去配置文件配置。在启动时自己会衡量,应该用哪个,不用哪个。
简化了依赖
不用配置服务器
没有增强功能,只是使开发更快捷
springboot快速入门:
先在maven导入两个依赖,后期创建项目时自动导入
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.1</version> </parent> 这个是规定版本的 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> 这个是配置依赖的 二合一就是自动配置的最优依赖,不会冲突
创建方法
@RequestMapping("/hello") public String Test(){ return "hello springboot"; }
创建一个引导类,写注解
@SpringBootApplication public class HelloApplication { public static void main(String[] args) { SpringApplication.run(HelloApplication.class); } }
运行
springboot配置文件:
有三个:
优先级最高application.properties
第二application.yml
第三application.yaml
YAML:
基本语法:数据前边要有空格,不同层级前面要有缩进。#是注释
server: • port: 8080 • address: 127.0.0.1 name: abc
数据类型:
1.map集合
person: name: zly
2.数组
adderss: • - beijing • - shanghai
3.纯量:单个的不可再分的值
msg1: ‘hello /n world’ msg2: ”hello /n world“ 双引号会识别转义字符 单引号不会
参数引用:${}
name: zly person: • name: ${name}
如何获取配置文件中的内容:
1.注解@value:麻烦,对应直接获取
2.Environment:使用注解@autowired直接注入,使用时调用。 private Environment env;
3.在实体类中使用注解@ConfigurationProperties(prefix = "person"),括号中的是说明是告诉在配置文件中哪个属性下的
在maven中添加一个依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
在配置文件中写配置的时候会提示
Profiles:
使用时要在不同环境,测试,开发,生产要来回切换,所以出现profiles来动态配置
profiles配置方式:
1.多个环境用多个配置文件,然后再applicaton.propert文件中用spring.peofiles.action=test来标明启动的环境是哪个
2.可以用application.yml文件来代替多个文件,在文件中用---来分隔多个环境。同样使用spring.peofiles.action=test来标明启动的环境是哪个
profiles激活方式:
1.在配置文件中用spring.peofiles.action=test来激活
2.在idea中类似tomcat设置,VMoptions -Dspring.peofiles.action=test
3.命令行参数激活
内部文件配置:
有加载顺序,有优先级,高优先级先生效,所有配置文件都会被加载
-
优先级排序: file:./config/: > file:./ > classpath:/config/ > classpath:/
外部配置文件:
和内部配置文件互补。比如打包之后发现配置有问题,可以更改配置文件重新打包,比较麻烦。使用外部配置文件可以覆盖,更加方便
SpringBoot整合junit:
加两个注释
@RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class)
1.@SpringBootTest(classes = 启动类名称.class) 基本等同于启动了整个服务,此时便可以开始功能测试。
2.运行器指定@RunWith 在JUnit中有很多个Runner,他们负责调用你的测试代码,每一个Runner都有各自的特殊功能,你要根据需要选择不同的Runner来运行你的测试代码。一般使用@RunWith(SpringRunner.class)
SpringBoot整合mybatis:
创建项目时要选两个,一个mybatis,一个sql
先在配置文件中写数据库信息
1.基于注解式
@Mapper加在类上,方法上加注解@Select....,里面写sql直接使用就行,不需要写映射文件
2.基于xml式:百度