基本特征
@ConfigurationProperties
- 与@Bean结合为属性赋值
- 与@PropertySource(只能用于properties文件)结合读取指定文件
- 与@Validation结合,支持JSR303进行配置文件值的校验,如@NotNull@Email等
@Value
- 为单个属性赋值
- 支持属性上的SpEL表达式
两者比较
@ConfigurationProperties | @Value | |
功能 | 批量注入配置文件中的属性 | 一个个指定 |
松散绑定 | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
复杂类型封装 | 支持 | 不支持 |
我们用简单的例子来说明一下。
假设在application.properties文件中这样写道:
1 student.name=zhangsan
2 student.age=25
3 student.class=mba
4 student.squad-leader=false
5 student.mail=zhangsan@gmail.com
6
7 student.maps.k1=aaa
8 student.maps.k2=bbb
9 student.maps.k3=ccc
10
11 student.lists=a,b,c
12
13 student.score.english=95
14 student.score.math=90
分别用上面两种绑定属性的方式写两个bean:
StudentCP类使用@ConfigurationProperties的方式来绑定属性,相关比较内容可以看代码上面的注释。
1 @Component
2 // @PropertySource表示加载指定文件
3 // @PropertySource(value = {"classpath:student.properties"})
4 @ConfigurationProperties(prefix = "student")
5 // prefiex表示指定统一前缀,下面就不用再写了
6 @Validated // ConfigurationProperties形式下支持JSR303校验
7 public class StudentCP {
8
9 private String name;
10
11 private Integer age;
12
13 // 支持松散绑定,可以将连接符转成驼峰命名
14 private Boolean squadLeader;
15
16 // 当前形式下支持JSR303数据校验,表示此属性值必须是email的格式
17 @Email
18 private String mail;
19
20 // 支持复杂类型封装对应
21 private Map<String, Object> maps;
22
23 private List<Object> lists;
24
25 private Score score;
26
27 }
StudentV类使用@Value的方式来绑定属性,注释中给出了简单的说明。
1 public class StudentV {
2
3 // 使用@Value的话只能给属性一一指定映射
4
5 @Value("student.name")
6 private String name;
7
8 // @Value形式支持SpEL表达式
9 @Value("#{13*2}")
10 // @Value("student.age")
11 private Integer age;
12
13 // @Value("true") // 可直接赋值
14 // 不能支持松散语法的绑定
15 @Value("student.squad-leader")
16 private Boolean squadLeader;
17
18 @Value("student.mail")
19 private String mail;
20
21 // 之后的map、list和对象等复杂形式对象@Value无法支持
22
23 }
小结
配置文件格式是yml或者properties两者都能够获取值;
如果说只想在某个业务逻辑中获取一下配置文件中的某个值,使用@Value;
如果说专门编写一个JavaBean来和配置文件进行映射,那么就使用@ConfigurationProperties.
其他
@ConfigurationProperties默认从全局配置文件中获取值,如果要从指定配置文件中获取值,那么需要通过@PropertySource来声明指定。
@PropertySource(value = "classpath:student.properties")
@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效。
我们自定义的配置文件,默认是不能注入(加载)到Spring的IoC容器中的,如果想在项目中使用自定义的配置文件,则需要通过@ImportResource来指定注入才能够最终使用。
@ImportResource(location = {"classpath:my-beans.xml"})
以前的项目中,我们都在xml中配置bean,但是实际当中(目前),我们不会使用这种方式来给项目添加组件,SpringBoot有推荐的方式,即使用注解。
@Configuration标注一个类,指明当前类是一个配置类,就是用来替代之前Spring使用xml配置的方式。(<bean id="" class=""></bean>)
1 @Configuration
2 public class MyConfig {
3
4 /**
5 * 将方法的返回值注入到容器中,容器中这个组件默认的id就是方法名
6 */
7 @Bean
8 public HelloService helloService() {
9 return new HelloService();
10 }
11 }
配置文件占位符
可以在***.properties中使用占位符使用一些函数,或者调用之前配置的一些内容:
1 ${ramdom.value}
2 ${random.int(10)}
3 ${student.name}
4 // 获取student.hobit的值,没有的话取冒号后面的缺省值
5 ${student.hobit:football}
来源:oschina
链接:https://my.oschina.net/u/4397674/blog/3446391