ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-12-01 10:02:52  阅读:136  来源: 互联网

标签:hobby SpringBoot 配置文件 Value person springframework import org


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

 

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

 

 

标签:hobby,SpringBoot,配置文件,Value,person,springframework,import,org
来源: https://blog.csdn.net/qq_45064423/article/details/121647798

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有