@ConfigurationProperties
是 Spring Boot 提供的一种获取配置文件数据的注解,只要指定配置文件中前缀,对应的配置文件数据就会自动填充到 Bean 中。
@ConfigurationProperties
可以作用在类或方法上。
一、作用于类
1. 在application.yml
(或application.properties
)中添加配置信息。
email:
sender: 又语
topic: ConfigurationProperties
content: Spring Boot @ConfigurationProperties demo
2. 定义配置类。
package com.example.demo;
import javax.annotation.PostConstruct;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "email")
public class EmailConfig {
private String sender;
private String topic;
private String content;
@PostConstruct
public void postConstruct() {
System.out.println(this.toString());
}
// Getter Setter 略
@Override
public String toString() {
return "{" +
" sender='" + getSender() + "'" +
", topic='" + getTopic() + "'" +
", content='" + getContent() + "'" +
"}";
}
}
3. 启动 Spring Boot 应用,可以看到启动日志中有如下打印。
{ sender='又语', topic='ConfigurationProperties', content='Spring Boot @ConfigurationProperties demo'}
二、作用于方法
1. 配置信息不变,定义对应的 Bean。
package com.example.demo;
public class Email {
private String sender;
private String topic;
private String content;
// Getter Setter 略
@Override
public String toString() {
return "{" +
" sender='" + getSender() + "'" +
", topic='" + getTopic() + "'" +
", content='" + getContent() + "'" +
"}";
}
}
2. 定义方法,使用@ConfigurationProperties
注解注入配置数据,注意要配合@Bean
注解一起使用。
package com.example.demo;
import javax.annotation.PostConstruct;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EmailConfig {
@PostConstruct
public void postConstruct() {
System.out.println(this.toString());
}
@Bean
@ConfigurationProperties(prefix = "email")
public Email email() {
return new Email();
}
}
3. 定义一个自动装配Email
类型属性的配置类,构造完成后打印此属性值判断第 2 步中的配置数据是否注入成功。
package com.example.demo;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Checker {
@Autowired
private Email email;
@PostConstruct
public void PostConstruct() {
System.out.println(email.toString());
}
}
4. 启动应用,日志中可以看到如下打印信息。
{ sender='又语', topic='ConfigurationProperties', content='Spring Boot @ConfigurationProperties demo'}