SpringBoot之@ConfigurationProperties详解

简介

该注解主要用于将配置文件中的属性映射到实体类属性;通过注解中的 prefix 属性筛选出配置文件中所有以 prefix 配置项开头的配置,然后映射到实体类中对应的属性上,使用方式有如下 2 种

  1. @ConfigurationProperties + @Component 组合注解
  1. 在 application.properties 配置文件中添加如下配置
user.userName = dufu
user.gender = male
  1. 在 User.class 类中添加如下代码
@Data
@Component
@ConfigurationProperties(prefix = "user1")
public class User {
    private String userName;
    private String gender;
}
  1. 在启动类 SpringbootStudyApplication.class 中测试一下
@SpringBootApplication
public class SpringbootStudyApplication {
    public static void main(String[] args) {
        // 1.返回 IOC 容器
        ConfigurableApplicationContext context = SpringApplication.run(SpringbootStudyApplication.class, args);
        // 2.查看初始化的 user 对象
        User user = (User)context.getBean("user");
        System.out.println(user); // User(userName=dufu, gender=male)
    }
}
  1. @ConfigurationProperties + @EnableConfigurationProperties 组合注解
  1. 在 User.class 中添加如下代码,注意:我们没有添加 @Component 注解
@Data
@ConfigurationProperties(prefix = "user")
public class User {
    private String userName;
    private String gender;
}
  1. 在配置类上添加 @EnableConfigurationProperties 注解,该注解的作用是:
  • 开启对实体类(User)属性配置绑定功能
  • 把组件(User)自动注入到容器中
@Configuration
@EnableConfigurationProperties(User.class)
public class AppConfig {
}
  1. 注入到 HelloController.class 中,测试一下
@RestController
public class HelloController {
    @Resource
    private User user;

    @GetMapping("/hello")
    public void hello() {
        System.out.println(user); // User(userName=dufu, gender=male)
    }
}

注意:这种方式注入的 user Bean 的默认名字为 user-com.study.springboot.entity.User;跟 @Component 注解生成的默认名字(类名首字符小写)不同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值