美文网首页
@ConstructorBinding

@ConstructorBinding

作者: CXY_XZL | 来源:发表于2022-04-20 23:52 被阅读0次

1.作用

通常与@ConfigurationProperties搭配使用,@ConfigurationProperties要求当前类要有属性的setter方法,而@ConstructorBinding的作用便是让@ConfigurationProperties通过当前类的构造函数将配置值绑定到当前类的属性上,这样就不需要属性的setter方法了,但是要有构造函数


2.使用条件

既然是将配置文件转化为java bean,那么就需要属性的setter方法,或者使用Lombok@setter或者@data注解;

如下:

@ConstructorBinding
@ConfigurationProperties(prefix = "acme")
@AllArgsConstructor
public class AcmeProperties {

    private Map<String, MyPojo> map = new HashMap<>();

}
@Configuration
@EnableConfigurationProperties(AcmeProperties.class)
public class AcmePropertiesConfiguration {
}
@RestController
public class DemoController {

    @Autowired
    private AcmeProperties acmeProperties;

    @GetMapping("/demo")
    public String demo(){
        return acmeProperties.toString();
    }

@ConstructorBinding不能与@Configuration@Component等注解搭配使用,会报错

相关文章

网友评论

      本文标题:@ConstructorBinding

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