@ConfigurationProperties 动态传值
时间: 2023-11-01 13:00:55 浏览: 49
@ConfigurationProperties 是一个注解,用于将外部配置文件中的属性值绑定到Spring Boot应用程序的特定类中。通过使用该注解,我们可以动态传递属性值给Spring Boot应用程序。
在使用 @ConfigurationProperties 注解时,需要做以下几个步骤:
1. 创建一个POJO类,用于存储属性值。这个类通常被称为配置类或属性类。
```java
@ConfigurationProperties(prefix = "example")
public class ExampleProperties {
private String property1;
private String property2;
// Getters and setters
}
```
2. 在主类或配置类上添加注解 `@EnableConfigurationProperties`,并指定要绑定的配置类。
```java
@SpringBootApplication
@EnableConfigurationProperties(ExampleProperties.class)
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
```
3. 在属性类中,使用 `@ConfigurationProperties` 注解,并指定属性的前缀。
4. 在外部配置文件(例如 application.properties 或 application.yml)中,添加需要绑定的属性值。
```yaml
example.property1=value1
example.property2=value2
```
现在,当应用程序启动时,属性文件中的属性值就会自动绑定到对应的属性类中。