@PropertySource:加载指定的配置文件

  1. 通过Spring Boot 全局配置文件与@Value 取赋值详解与 @ConfigurationProperties 对比已经知道使用“@Value”注解与“@ConfigurationProperties”可以从全局配置文件“application.properties”或者“application.yml”中取值然后为需要的属性赋值

  2. 但是如果应用比较大的时候,如果所有的内容都当在一个文件中,如“application.properties”或者“application.yml”中时,就会显得比较臃肿,同时也不太好理解和维护

  3. 可以将一个文件拆分为多个,此时使用@PropertySource即可解决问题

  4. @PropertySource 用于加载指定的配置文件

image-20200107120913180

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {
/**
* <bean class="Person">
* <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
* <bean/>
*/
//lastName必须是邮箱格式
// @Email
//@Value("${person.last-name}")
private String lastName;
//@Value("#{11*2}")
private Integer age;
//@Value("true")
private Boolean boss;

@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;

Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别。

想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上

1
2
@ImportResource(locations = {"classpath:beans.xml"})
导入Spring的配置文件让其生效

不推荐来编写Spring的配置文件

1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="helloService" class="com.kylin.springboot.service.HelloService"></bean>
</beans>

image-20200107122438488

SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式

  1. 配置类@Configuration——>Spring配置文件.@Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件

  2. 使用@Bean给容器中添加组件,相当于在Springl配置文件中用bean标签添加组件。将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
*
* 在配置文件中用<bean><bean/>标签添加组件
*
*/
@Configuration
public class MyAppConfig {

//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
@Bean
public HelloService helloService02(){
System.out.println("配置类@Bean给容器中添加组件了...");
return new HelloService();
}
}

配置文件占位符${}

随机数

随机数 含义
${random.uuid} 取出来的是随机数
${random.int} 整型数
${random.long} 长整型数
${random.int(10)} 10以内的整型数
${random.int[1024,65536]} 数组中的数据

属性配置占位符

  • 可以在配置文件中引用前面配置过的属性(优先级前面配置过的这里都能用)
  • ${app.name:默认值}来指定找不到属性时的默认值

image-20200107160940787

1
2
3
4
5
6
7
8
9
person.last-name=张三${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15