SpringBoot
- SSM的问题:jar包容易冲突,配置文件过于臃肿
- SpringBoot:内置了Tomcat插件,无需配置文件,解决jar包冲突
发展历史
EJB:spring诞生前流行的框架,相对于Spring来说过于臃肿
- springBoot:构建一切的产品
- springCloud 协调一切的产品
SpringBoot特点
- 约定优于配置
- 专注于业务逻辑之间思维切换
- 基于spring的开发提供更快入门体验
- 开箱即用,没有代码生成,无需XML配置
- 支持修改默认配置,满足要求
- 提供大型项目中常见的非功能特性,如嵌入tomcat服务,安全,指标,健康检测,外部配置等
SpringBoot核心功能
- 起步依赖:本质是Maven项目中对象模型中的标签.它定义其SpringBoot对其它库的传递依赖,依赖加在一起课支持某项功能.使得SpirngBoot具备了构建一切的能力,整合所有牛逼的框架
- 自动配置: 基于约定优于配置思想,配置基本都可以走默认值
SpringBoot入门
方式一
- 添加SpringBoot依赖 spring-boot-starter-parent spring-boot-starter-web(web启动器)
- 起步依赖(起步引导类) SpringApplication.run(要加载的类的字节码对象,main函数参数),一个工程一个
- 自动装配 @SpringBootApplication 标识当前类是SpringBoot启动
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
SpringBoot配置文件
注意:两种文件只能用一个
application.properties 方式一
##修改tomcat的启动端口号
servier.port=8080
##设置项目访问根目录 默认值 /
server.servlet.context-path=/demo
application.yml 方式二 推荐
#在yml语法中,空格非常非常敏感 冒号后边有空格隔开
name: Steven
##配置对象数据
User:
name: LiZhengKai
age: 18
addr: ZhuHai
#对象配置方式二
user1: {
name: LiZhengKai,age: 18,addr: ZhuHai}
#配置集合
userList:
- LiZhengKai
- WuLiLI
#配置集合方式二
userList2: [LiZhengKai,WuLiLi]
#配置集合重点对象
userListObj:
- name: LiZhegnKai
age: 18
addr: ZhuHai
- name: WuLiLi
age: 18
addr: HeYuan
注意:冒号后边一定要手动加入空格
配置文件与映射类的属性映射方式
使用@Value映射 (简单属性推荐)
//这样子配置文件中的name属性就被赋予到name中
//user.name是springboot内置属性,读取到的是计算机的名字
@Value("${user.name}")
private String name;
使用@ConfigurationProperties (较为复杂推荐)
//在实现类中添加@ConfigurationProperties注解 prefix属性表示配置文件中的哪个数据对象
@ConfigurationProperties(prefix="user1")
注意:要使用@Component进行托管,表示这是spring的一个bean对象
使用 Environment (复制属性推荐)
//注入Enviroment
@Autowired
private Environment env;
//获取 可以获取属性,也可以获取属性对象中的属性
env.getProperty("name");
env.getProperty("user.name")
P r o f i l e
企业中不同的环境
- 开发环境 程序员 本地开发,局域网开发
- 测试环境 测试工程师
- 生产环境 真实线上
通过active指定选用配置环境
application.properties
spring.profiles.active=test
application.properties
spring:
profiles:
active: test
- application-dev.properties/yml
- application-test.properties/yml
- application-pro.properties/yml
可以在jvm中配置-Dspring.profiles.active=dev 它的级别高于在配置文件中的指定配置
SpringBoot整合Mybatis
- service层的实现类要使用
@Servcie
注解 - doa层接口要使用
@Mapper
注解 - resource目录中要有映射文件
application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.13.100/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#映射文件加载
mybatis.mapper-locations=classpath:/mapper/*.xml
#配置别名
mybatis.type-aliases-package=com.itheima.integration.domain
#配置日志输出 主要输出sql语句
logging.level.com.itheima.integration.dao=debug
SpringBoot整合Spring Data Redis
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>