SpringBoot 2@Value与 @ConfigurationProperties 获取配置文件的属性值比较

application.yml文件内容如下

person:
  name: zhangshan
  age: 18
  hobby: [篮球,羽毛球]

测试类yamlTest如下

import com.douya.example.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class yamlTest {
    @Autowired
    Person person;

    @RequestMapping("/person")
    public Person hello(){
        return person;
    }
}

使用@ConfigurationProperties注解将配置文件中的信息映射到Person类如下:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix="person")#prefix中的值必须为小写
public class Person {
    private String name;
    private Integer age;
    private String[] hobby;
}

postman访问结果如下

而使用@Value注解将配置文件的信息映射到Person类时代码及报错如下

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Data
@Component
public class Person {
    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;
    @Value("${person.hobby}")
    private String[] hobby;
}

报错如下:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'yamlTest': Unsatisfied dependency expressed through field 'person'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'person': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'person.hobby' in value "${person.hobby}"

经查阅得知@Value不支持复杂类型封装,所以对string[] 类型的hobby的值注入失败。

下面附上@Value注解和@ConfigurationProperties的区别

参考:

springboot ---配置 @ConfigurationPropeties与 @value的区别_NDSoumig的博客-CSDN博客

 

 注:菜鸟的第一篇博客,记录学习过程中遇到的问题。写的不好的地方,请指出谢谢

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值