解决springboot项目中@Value注解参数值为null的问题

1、错误场景:

springboot项目中在.properties文件(.yml)文件中配置了属性值,在Bean中使用@Value注解引入该属性,Bean的构造器中使用该属性进行初始化,此时有可能会出现属性值为null,造成初始化程序的错误

2、错误原因:

因为Bean的构造器调用是在@Value属性赋值之前进行的,所以造成了属性还没有赋值,就被调用的情况。

3、解决方案:

将构造器中需要使用的@Value属性作为构造器的参数,确保构造器中使用该属性之前,属性已经得到初始化

理论先行,代码跟上(^_^)

(1).yml配置文件中配置系统参数值 file.upload-dir

file:
  upload-dir: /Users/lc/temp/

(2)FileStorageService 的构造器需要使用使用 file.upload-dir 属性

@Service
public class FileStorageService {
  /* @Value("${file.upload-dir}")
    private String uploadDir; */
public FileStorageService(@Value("${file.upload-dir}") String uploadDir) throws ServiceException { this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize(); try { Files.createDirectories(this.fileStorageLocation); } catch (Exception e) { throw new Exception(e); } } }

(3)now,问题解决了。

转载于:https://www.cnblogs.com/zhoujl-5071/p/10371321.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值