【SpringBoot2 从0开始】底层注解 - @ConfigurationProperties 配置绑定

SpringBoot配置绑定与JavaBean
本文介绍了如何在Java中解析配置文件并将其内容绑定到JavaBean中,以及SpringBoot如何简化这一过程。通过@ConfigurationProperties注解,可以方便地将配置文件中的属性与JavaBean字段进行绑定,实现自动化配置。此外,还提到了使用@EnableConfigurationProperties替代@Component的方式,适用于第三方库中未添加@Component注解的类。最后,示例展示了配置绑定在实际应用中的验证步骤。

我们通常会把一些经常变动的东西放到配置文件里。

比如之前写在配置文件application.properties里的端口号server.port=8080,另外常见的还有数据库的连接信息等等。

那么,我的数据库连接信息放在配置文件里,我要使用的话肯定得去解析配置文件,解析出的内容在 bean 里面去使用。

整个场景其实就是把配置文件里的所有配置,绑定到 java bean 里面

要完成这个场景,基于 java 原生代码编写还是有点麻烦的。通常会做一个封装,读取到properties文件中的内容,并且把它封装到JavaBean中:

public class getProperties {
     public static void main(String[] args) throws FileNotFoundException, IOException {
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
         while(enum1.hasMoreElements()) {
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //封装到JavaBean
             ... ...
         }
     }

这里就是使用Properties类来加载配置文件a.properties,然后遍历配置文件中的每一个k-v,获取之后就可以用到对应的地方。

在 springboot 中简化了这个过程,这就是配置绑定。

配置绑定

通过使用注解@ConfigurationProperties来完成配置绑定,注意需要结合@Component使用。

新建一个组件Car,有2个属性分别是品牌和价格:

@Component
public class Car {
    private String brand;
    private Integer price;
// get set tostring 就不贴了

在配置文件application.properties,设置一些属性值,比如:

mycar.brand=QQ
mycar.price=9999

使用@ConfigurationProperties注解,加到组件上:

@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;
... ...

传进去的 prefix 是配置文件里的前缀,这里就是 mycar。

验证

现在来测试一下是否绑定成功,在之前的HelloController继续增加一个控制器方法:

@RestController
public class HelloController {

    @Autowired
    Car car;

    @RequestMapping("/car")
    public Car car() {
        return car;
    }

    @RequestMapping("/hello")
    public String Hello() {
        return "Hello SpringBoot2 你好";
    }
}

部署一下应用,浏览器访问http://localhost:8080/car:

绑定成功。

另一种方式

除上述方法之外,还可以使用@EnableConfigurationProperties + @ConfigurationProperties的方式来完成绑定。

注意,@EnableConfigurationProperties注解要使用在配置类上,表示开启属性配置的功能:

//@ConditionalOnBean(name = "pet1")
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = true)
@ImportResource("classpath:beans.xml")  //配置文件的类路径
@EnableConfigurationProperties(Car.class) //开启属性配置的功能
public class MyConfig {

    @Bean("user1")
    public User user01(){
        User pingguo = new User("pingguo",20);
        pingguo.setPet(tomcatPet());
        return pingguo;
    }

    @Bean("pet22")
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}

@EnableConfigurationProperties(Car.class)传入要开启配置的类,这可以自动的把 Car 注册到容器中,也就是说之前 Car 上的@Component就不需要了。

//@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;

重新部署访问下地址,依然可以。

关于第二种的使用场景,比如这里的 Car 是一个第三方包里的类,但是人家源码没有加@Component注解,这时候就可以用这种方式进行绑定。

最后,要记住当使用@ConfigurationProperties(prefix = "mycar")这个配置绑定时,是跟 springboot 核心配置文件 application.properties文件的内容建立的绑定关系。

<think>我们正在讨论Spring框架中的@Value注解,特别是关于它不支持松散绑定的特性。松散绑定SpringBoot中一个特性,允许配置属性名称以更灵活的方式书写(例如,驼峰命名、短横线分隔或下划线分隔),而仍然能映射到同一个配置项。根据引用[4]的表格,我们可以看到:-@Value注解不支持松散绑定-@ConfigurationProperties支持松散绑定这意味着:1.使用@Value注解时,配置属性名称必须严格匹配(包括大小写和分隔符)。2.而使用@ConfigurationProperties时,配置属性名称可以采用不同的书写风格(例如,`my.property`、`myProperty`、`my_property`)并映射到同一个字段。示例说明:假设我们有一个配置项:`user.first-name`,在属性文件(如application.properties)中这样定义:```propertiesuser.first-name=John```使用@Value注入:```java@Value("${user.first-name}")//正确,属性名完全匹配(短横线分隔)privateStringfirstName;```但是,如果我们尝试使用驼峰形式:```java@Value("${user.firstName}")//错误!这样注入会失败,因为属性文件中是user.first-nameprivateStringfirstName;```同样,使用下划线形式也会失败:```java@Value("${user.first_name}")//错误!因为属性文件中没有定义这个名称privateStringfirstName;```而在@ConfigurationProperties中,我们可以这样写:```java@ConfigurationProperties(prefix="user")publicclassUserProperties{privateStringfirstName;//对应配置中的user.first-name或user.firstName或user.first_name//getter和setter}```在UserProperties类中,SpringBoot的松散绑定规则允许我们使用驼峰形式的字段名(firstName),而配置文件中可以写成:user.first-name(推荐,短横线分隔)或user.firstName(驼峰)或user.first_name(下划线)因此,如果你希望配置项的名称可以灵活书写,应该使用@ConfigurationProperties而不是@Value。总结:@Value要求属性名严格匹配,不支持松散绑定,而@ConfigurationProperties支持。相关问题:1.在SpringBoot中,如何实现配置属性的松散绑定2.@ConfigurationProperties注解除了支持松散绑定外,还有哪些优势?3.如何在SpringBoot应用中使用@ConfigurationProperties来批量注入配置属性?</think> ### @Value注解不支持松散绑定的含义及示例 #### **一、松散绑定(Relaxed Binding)概念** 在Spring Boot配置中,松散绑定是指属性名称可以有多种等效书写形式。例如: ```properties # 等效写法 spring.datasource.url=... SPRING_DATASOURCE_URL=... spring.datasource-url=... spring.datasource_url=... ``` #### **二、@Value的严格匹配特性** 引用[4]明确指出:**@Value不支持松散绑定**。意味着: 1. **属性名必须严格匹配**(包括大小写和分隔符) 2. **不同命名风格不可互换**(驼峰、短横线、下划线等) 3. **不会自动转换属性名格式** #### **三、示例对比** **配置项 `user.account-balance`:** ```properties # application.properties user.account-balance=1000 ``` **使用@Value注入:** ```java @Component public class PaymentService { // 严格匹配才能成功 @Value("${user.account-balance}") private int balance; // 成功注入:属性名完全一致 [^2][^5] // 其他形式均失败 @Value("${user.accountBalance}") private int balance1; // 失败:驼峰命名 != 短横线命名 @Value("${user.account_balance}") private int balance2; // 失败:下划线 != 短横线 @Value("${USER.ACCOUNT-BALANCE}") private int balance3; // 失败:大小写敏感 } ``` #### **四、@ConfigurationProperties对比** 引用[4]的对比表格显示:**@ConfigurationProperties支持松散绑定** ```java @ConfigurationProperties(prefix = "user") public class UserConfig { // 以下三种写法均可成功注入 private int accountBalance; // 驼峰命名 private int account_balance; // 下划线命名 private int account-balance; // 短横线命名 } ``` #### **五、根本原因** 1. **@Value实现机制**: - 直接读取属性源中的字面值 - 不会对属性名进行格式转换 - 底层通过`PropertySourcesPlaceholderConfigurer`处理[^1][^3] 2. **@ConfigurationProperties机制**: - 使用`RelaxedDataBinder`进行名称转换 - 支持多种命名风格的自动映射 #### **六、最佳实践建议** 1. 需要严格匹配时使用@Value: ```java // 确保属性名完全一致 @Value("${exact.property.name}") ``` 2. 需要命名灵活性时改用: ```java @ConfigurationProperties(prefix = "app") public class AppConfig { private String flexibleName; } ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值