Springboot概述
简介
Spring Boot是基于Spring框架开发的全新框架,其设计目的是简化新Spring应用的初始化搭建和开发过程。
Spring Boot整合了许多框架和第三方库配置,几乎可以达到开箱即用
优点
- 可快速构建独立的Spring应用
- 直接嵌入Tomcat、Jetty和Undertow服务器(无需部署WAR文件)
- 提供依赖启动器简化构建配置
- 极大程度的自动化配置Spring和第三方库
- 提供生产就绪功能
- 极少的代码生成和XML配置
Springboot案例
- 选择版本
以2.4.5为例子 - 添加一个web场景启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 创建Controller
@Controller
public class UserController {
@RequestMapping("test")
public String test(){
System.out.println("UserController.test");
return "";
}
}
启动类要在根目录,扫描启动类所在包以及子包
`
@SpringBootApplication
@SpringBootConfiguration
当前启动类为放到Spring容器
@EnableAutoConfiguration
@AutoConfigurationPackage
扫描当前包,完成自己编写的类交给Spring管理
@Import({AutoConfigurationImportSelector.class})
完成Spring和SrpingMVC配置的内容,自动配置
Spring Boot核心配置和注解
全局配置文件
常用有Application.yaml 配置文件和Application.properties文件,常用前者,后者等级比前者高
##key:(空格)value
server:
port: 8081
path: /hello
spring:
datasource:
driver-class-name:
url:
data-username:
data-password:
mvc:
view:
prefix:
suffix:
配置文件属性值注入
- 使用 @Component和@ConfigurationProperties(prefix = “xxx”)
例子
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private int id;
public void setId(int id) {
this.id = id;}}
注意:使用@ConfigurationProperties注解批量注入属性值时,要保证配置文件中的属性与对应实体类的属性一致,否则无法正确获取并注入属性值。
- 使用@Value注入属性
@Component
public class Person {
@Value("${person.id}")//使用@Value注解对每一个属性注入设置,免去了属性setXX()方法
private int id;
}
- 使用@PropertySource加载配置文件
创建test.yml
@Configuration
@PropertySource("classpath:test.properties
@EnableConfigurationProperties(MyProperties.class)
@ConfigurationProperties(prefix = "test}
public class MyProperties {
}
多环境配置
在实际开发中,应用程序通常需要部署到不同的运行环境中,例如开发环境、测试环境、生产环境等。不同的环境可能需要不同的环境配置,针对这种情况,不可能手动变更配置文件来适应不同的开发环境,此时就需要对项目进行多环境配置。
- 多环境配置文件
文件名 | 作用 |
---|---|
application_dev.yaml | 配置开发环境 |
application_prod.yaml | 配置生产环境 |
application_test.yaml | 配置测试环境 |
在application.yaml中配置
# 开发环境
spring:
profiles:
active: dec
# 生产环境
spring:
profiles:
active: prod
# 测试环境
spring:
profiles:
active: test
- 在主配置配置中分别配置