原理
在 Java 中,@ConfigurationProperties 注解用于将配置文件中的属性绑定到一个配置类的实例上。@EnableConfigurationProperties 注解则用于启用对 @ConfigurationProperties 注解的支持。
- 实现步骤
首先,你需要创建一个配置属性类,该类使用 @ConfigurationProperties 注解:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "my.properties")
public class MyProperties {
private String name;
private int age;
// Getter 和 Setter 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
然后,你需要在主应用类上使用 @EnableConfigurationProperties 注解来启用 @ConfigurationProperties 注解的支持:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(MyProperties.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
最后,你需要在 application.properties 或 application.yml 文件中添加相应的配置:
# application.properties
my.properties.name=John
my.properties.age=30
或者
# application.yml
my:
properties:
name: John
age: 30
当你启动 Spring Boot 应用程序时,Spring 容器会自动读取配置文件中的值,并将它们绑定到 MyProperties 类的实例上。这个实例会被 Spring 容器管理,并且可以在应用程序的其他部分中注入和使用。