如何禁止ConfigurationProperties属性名自动转换为小写?
时间: 2024-05-28 07:07:42 浏览: 6
在Spring Boot中,可以使用@ConfigurationProperties注解来绑定外部配置文件中的属性到Java对象上。默认情况下,Spring Boot会将@ConfigurationProperties属性名自动转换为小写,并使用“-”来分隔多个单词。如果想禁止这种默认行为,可以使用以下两种方式:
1. 使用@ConstructorBinding注解
在Java类上添加@ConstructorBinding注解,并且在类的构造方法上添加@ConfiguredPropertiesBinding注解,示例如下:
```
@ConfigurationProperties(prefix = "my-config")
@ConstructorBinding
public class MyConfig {
private String myProperty;
public MyConfig(@ConfigurationPropertiesBinding String myProperty) {
this.myProperty = myProperty;
}
// getters and setters
}
```
这样做的好处是,属性名不会被自动转换为小写,而且可以更加灵活地使用构造方法。
2. 使用Binder API
使用Binder API可以更加细粒度地控制属性名的转换。示例如下:
```
@ConfigurationProperties(prefix = "my-config")
public class MyConfig {
private String myProperty;
public void setMyProperty(String myProperty) {
this.myProperty = myProperty;
}
// getters and setters
}
```
然后,在需要绑定属性的地方,使用Binder API来手动绑定属性,示例如下:
```
@Configuration
public class MyConfigConfiguration {
@Bean
public MyConfig myConfig(ConfigurationPropertySource configurationPropertySource) {
Binder binder = new Binder(configurationPropertySource);
return binder.bind("my-config", MyConfig.class).orElse(new MyConfig());
}
}
```
这样做的好处是,可以更加细粒度地控制属性名的转换,也可以更加方便地使用多种绑定方式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)