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博客

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

猜你喜欢

转载自blog.csdn.net/qq_45064423/article/details/121647798