springboot项目,使用@EnableConfigurationProperties、@ConfigurationProperties 注解读取配置属性值,并绑定到配置类上

原理

在 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 容器管理,并且可以在应用程序的其他部分中注入和使用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值