ConfigurationProperties注解使用

该注解的作用是将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注解,通过反射)。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容