@ConfigurationProperties注解
@ConfigurationProperties是springboot提供读取配置文件的一个注解。其对应的bean的后置处理器为**ConfigurationPropertiesBindingPostProcessor**
Spring源码中大量使用了ConfigurationProperties注解,比如server.port
就是由该注解获取到的,通过与其他注解配合使用,能够实现Bean的按需配置。
该注解有一个**prefix**属性,通过指定的前缀,绑定配置文件中的配置,该注解可以放在类上,也可以放在方法上。
@ConfigurationProperties注解源码:
// IntelliJ API Decompiler stub source generated from a class file
// Implementation of methods is not available
package org.springframework.boot.context.properties;
@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Documented
public @interface ConfigurationProperties {
@org.springframework.core.annotation.AliasFor("prefix")
java.lang.String value() default "";
@org.springframework.core.annotation.AliasFor("value")
java.lang.String prefix() default "";
boolean ignoreInvalidFields() default false;
boolean ignoreUnknownFields() default true;
}
在SpringBoot中,当需要获取到配置文件数据时,除了可以用Spring自带的@Value注解外,SpringBoot提供了一种更加方便的方式:@ConfigurationProperties。只要在bean上添加上这个注解,指定好配置文件的前缀,那么对应的配置文件数据就会自动填充到bean中。
举个栗子,现在有如下配置:
myconfig.name=test
myconfig.age=22
myconfig.desc=这是我的测试描述
添加对应的配置类,并添加上注解@ConfigurationProperties,指定前缀为myconfig:
@Component
@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {
private String name;
private Integer age;
private String desc;
//get/set 略
@Override
public String toString() {
return "MyConfig [name=" + name + ", age=" + age + ", desc=" + desc + "]";
}
}
添加使用:
public static void main(String[] args) throws Exception {
SpringApplication springApplication = new SpringApplication(Application.class);
// 非web环境
springApplication.setWebEnvironment(false);
ConfigurableApplicationContext application = springApplication.run(args);
MyConfig config = application.getBean(MyConfig.class);
log.info(config.toString());
application.close();
}
可以看到输出log:
com.cml.chat.lesson.lesson3.Application - MyConfig [name=test, age=22, desc=这是我的测试描述]