美文网首页
ConfigurationProperties注解使用

ConfigurationProperties注解使用

作者: Bug之王 | 来源:发表于2021-02-24 23:58 被阅读0次

该注解的作用是将spring-boot 配置文件中的属性批量地注入到指定的类上。

@Component
@ConfigurationProperties(prefix ="student")
public class Student {
    private String name;
    private int age;
    private List<String> likes;
    private Map<String, Integer> scoreMap;
}

配置文件

student: 
    name: xiaoming
    age: 10
    likes: [篮球,足球]
    scoreMap: {语文:90, 数学:95}

如上述配置可以将配置文件中以student开头的属性批量地注入到Student类中。

@ConfigurationProperties可以配合@Component使用,也可以配合
@EnableConfigurationProperties注解使用,如下代码也可以起到相同的作用,将@ConfigurationProperties配置的类的bean注入到spring 容器。

@ConfigurationProperties(prefix =”student“)
public class Student {
    private String name;
    private int age;
    private List<String> likes;
    private Map<String, Integer> scoreMap;
}

@Service
@EnableConfigurationProperties(Student.class)
public class StudentService {
    @Autowired
    private Student student;
}

@ConfigurationProperties注解的注入匹配方式比较宽松,如类的scoreMap属性,对应的配置文件可以是scoreMap,也可以是score_map,score-map。

另外,@ConfigurationProperties的实现是通过类属性的setter,所以注入的属性必须有setter方法(这点区别于@Value注解,通过反射)。

相关文章

网友评论

      本文标题:ConfigurationProperties注解使用

      本文链接:https://www.haomeiwen.com/subject/tvoefltx.html