简介
该注解主要用于将配置文件中的属性映射到实体类属性;通过注解中的 prefix 属性筛选出配置文件中所有以 prefix 配置项开头的配置,然后映射到实体类中对应的属性上,使用方式有如下 2 种
- @ConfigurationProperties + @Component 组合注解
- 在 application.properties 配置文件中添加如下配置
user.userName = dufu
user.gender = male
- 在 User.class 类中添加如下代码
@Data
@Component
@ConfigurationProperties(prefix = "user1")
public class User {
private String userName;
private String gender;
}
- 在启动类 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)
}
}
- @ConfigurationProperties + @EnableConfigurationProperties 组合注解
- 在 User.class 中添加如下代码,注意:我们没有添加 @Component 注解
@Data
@ConfigurationProperties(prefix = "user")
public class User {
private String userName;
private String gender;
}
- 在配置类上添加 @EnableConfigurationProperties 注解,该注解的作用是:
- 开启对实体类(User)属性配置绑定功能
- 把组件(User)自动注入到容器中
@Configuration
@EnableConfigurationProperties(User.class)
public class AppConfig {
}
- 注入到 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 注解生成的默认名字(类名首字符小写)不同