springboot的5种读取配置方式(6):总结properties,yml,xml的区别

通过springboot的5种读取配置方式(1):直接读取bean

springboot的5种读取配置方式(2):通过config读取指定文件

springboot的5种读取配置方式(3):通过application.properties读取

springboot的5种读取配置方式(4):通过application.yml读取

springboot的5种读取配置方式(5):通过applicationContext.xml读取

我总结下:

1.config读取:

需要在实体类中声明@Configuration

读取文件是通过@ComponentScan()

比如:


//默认从根目录扫描
@Configuration

//扫描指定包路径
@ComponentScan("springboot.config")

2.读取application文件:

.properties和.yml文件是通过在实体类中加入 @Value注入的

读取文件都是通过@PropertySource()

比如:

.properties文件的格式是key=value

.yml文件格式是key:value


student.name= 小康
student.age=15


#yml文件的配置格式是key:value
student:
  name: 小明
  age : 25

@Value("${student.name}")
private String name;
@Value("${student.age}")
private  int age;

//读取resources目录下的application.properties
@PropertySource("classpath:application.properties")

//读取resources目录下的application.yml
@PropertySource("classpath:application.yml")

需要在pom.xml添加依赖:

<!-- 这个依赖会把配置文件的值注入到@value里面 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
</dependency>

3.如果application.properties,application.yml在同一个resources目录下,默认是读取第一个配置文件的

比如:


默认读取的是application.properties文件里的信息。

4.如果存在application.properties或者application.yml的,你把xml命名为application.xml时会报错的:

即使我把application.properties或者application.yml删掉也会报错:


但我把application.xml改名为applicationContext.xml时运行就正常了。

5.applicationContext的读取是用@ImportResource

//读取resources目录下的applicationContext.xml
@ImportResource("classpath:applicationContext.xml")
我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。