@ConfigurationProperties + @Component
在 Spring Boot 项目中,我们可以将大量的参数配置在 application.properties 或 application.yml 文件中,通过 @ConfigurationProperties 注解,我们可以方便的获取这些参数值
@ConfigurationProperties:prefix===>属性的前缀
/**
* @Author wem.jie
* @Description 只有容器中的组件才拥有SpringBoot强大功能
* @Date 2021/1/29 8:43
**/
@Data
@Component
@ConfigurationProperties(prefix = "wj.person")
public class Person {
private String personName;
private Integer age;
}
配置文件
wj.person.personName=wen.jie
wj.person.age=18
主启动类:
@SpringBootApplication
public class Boot2TestApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run =
SpringApplication.run(Boot2TestApplication.class, args);
Person person = run.getBean(Person.class);
System.out.println(person);
}
}
@EnableConfigurationProperties +@ConfigurationProperties
@Data
@ConfigurationProperties(prefix = "wj.person")
public class Person {
private String personName;
private Integer age;
}
在配置类上面加上@EnableConfigurationProperties
//开启Person配置绑定功能
//把Person组件自动注册到容器中
@EnableConfigurationProperties(Person.class)
@SpringBootApplication
public class Boot2TestApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run =
SpringApplication.run(Boot2TestApplication.class, args);
Person person = run.getBean(Person.class);
System.out.println(person);
}
}
宽松绑定
以下配置,无论哪一种都会被绑定到对象属性上。
wj.person.personName=wen.jie
wj.person.person-Name=wen.jie
wj.person.person_Name=wen.jie
wj.person.personname=wen.jie
wj.person.PERSON-name=wen.jie
自动提示
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
然后重新启动应用后,以后写配置文件,自定义的都有提示了。