SpringBoot的@ConfigurationProperties
与@Value
都可以将全局配置文件的值赋给指定的属性
-
@ConfigurationProperties
支持批量注入,该注解定义在类上,可以设置prefix
属性指定前缀
如:@Component @ConfigurationProperties(prefix = "test") public class Student { private String name; private Integer age; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; }
application.properties
文件:test.name=fei test.age=20 test.sex=man
测试可以发现,Student的同名属性成功赋上了值
测试代码@RunWith(SpringRunner.class) @SpringBootTest public class FirstspringbootApplicationTests { @Autowired private Student student; @Test public void contextLoads() { System.out.println(student); } }
-
@Value
常常用于给单个属性赋值,支持SPEL(spring表达式),注解直接用于属性上
如:@Component public class Student { @Value("${test.name}") private String name; @Value("${test.age}") private Integer age; @Value("${test.sex}") private String sex; @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } }
SPEL:spring表达式就是以${}这种方式取值,或者以#{2*8}这种形式计算表达式
最后测试结果是一致的
-
@Value
使用@Value("${test.name}")
这种方式取值,要是在配置文件里面没有定义test.name
,那启动会报错。而@ConfigurationProperties
没有同名属性也不会报错。 -
@ConfigurationProperties
赋值必须需要该属性提供get
和set
方法,而@Value
则不需要 -
补充:
修改SpringBoot的默认配置就是通过`@ConfigurationProperties映射回去的
比如 http编码自动配置
看HttpEncodingAutoConfiguration.class
提供的配置类HttpProperties.class
在
HttpProperties.class
类上就提供了
@ConfigurationProperties(prefix = "spring.http")
注解
继续看,在HttpProperties.class
类中定义了一个静态内部类
public static class Encoding
Encoding
这个类有一个charset属性
可以看到默认编码是UTF-8
那根据我们之前学的知识知道,我们可以在全局配置文件里面修改默认的http编码
使用方法就是spring.http.Encoding.charset=xxxx
因为启动的时候@ConfigurationProperties注解会为相应属性注入值
修改其他默认属性,原理大同小异
使用的版本
2.1.4.RELEASE