一、Yaml配置文件
配置文件除了可以使用application.properties类型,还可以是application.yml或application.yaml
格式如下:
1、多个yml配置文件:在spring boot中是被允许的。
这些配置文件的名称必须为application-***.yml,并在这些配置文件必要要在application.yml配置文件中激活之后才可以使用。
2、如果properties和yml配置文件同时存在springboot项目中;那么这两类型配置文件都有效。
在两个配置文件中如果存在同名的配置项的话会以properties文件的为主。
实例:在两个配置文件中如果存在同名的配置项的话会以properties文件的为主。
application.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
application.yml
jdbc:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm
username: root
password: root
测试发现,注册的是test数据源
实例:多个yml文件配置
application-a.yml
qq:
url: http://www.qq.com
application-b.yml
baidu:
url: http://www.baidu.com
application.yml 激活多个配置文件
#激活多个配置文件
spring:
profiles:
active: a,b
Controller
//@RestController 整合了@Controller 和 @ResponseBody
@RestController
public class HelloController {
@Autowired
private DataSource dataSource;
@Value("${baidu.url}")
private String baiduUrl;
@Value("${qq.url}")
private String qqUrl;
@GetMapping("/hello")
public String hello(){
System.out.println("baiduUrl="+baiduUrl);
System.out.println("qqUrl="+qqUrl);
System.out.println("dataSource="+dataSource);
return "hello ,Spring Boot!";
}
}
注意:SpringBoot启动时,会自动将application.properties或application.yml加载到容器里。
二、SpringBoot 自动配置流程
为什么只加载 spring-boot-starter-web 坐标,就可以启动Springmvc的web项目?
1、启动引导类中 @SpringBootApplication注解
(1)@SpringBootConfiguration 指定该类为配置类
(2)@EnableAutoConfiguration
(3)@ComponentScan 扫描当前包或子包里面使用spring注解的组件
推荐阅读: https://www.jianshu.com/p/39ee4f98575c
2、SpringApplication.run()方法