服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 解决SpringBoot @value注解取不到值的问题

解决SpringBoot @value注解取不到值的问题

2021-09-28 09:38FanClys Java教程

这篇文章主要介绍了解决SpringBoot @value注解取不到值的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

关于@value的springapplication容器的问题

1.在src/main/resources下创建stu.properties文件

  1. ##
  2. student.name=Tom
  3. student.age=22
  4. student.birthday=1996/01/10
  5. student.sex=true
  6. student.hobbies[0]=swimming
  7. student.hobbies[1]=basketball
  8. student.skills[0]=programming
  9. student.skills[1]=test
  10. student.address.province=henan
  11. student.address.city=zhengzhou

2.创建实体类

  1. package com.fcy.entity;
  2. import java.util.Arrays;
  3. import java.util.Date;
  4. import java.util.List;
  5. import java.util.Map;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.PropertySource;
  8. import org.springframework.stereotype.Component;
  9. @Component
  10. @PropertySource({"classpath:stu.properties"})
  11. public class Student {
  12. @Value("${student.name}")
  13. private String name;
  14. @Value("${student.age}")
  15. private int age;
  16. @Value("${student.sex}")
  17. private boolean sex;
  18. @Value("${student.birthday}")
  19. private Date birthday;
  20. private String[] hobbies;
  21. private List<String> skills;
  22. private Map<String, Object> address;
  23. //省略getter和setter方法
  24. }

3.错误的方法

  1. @RestController
  2. public class StudentController {
  3. @RequestMapping("/getStu")
  4. public Student getStu() {
  5. Student stu=new Student();
  6. System.out.println(stu);
  7. return stu;
  8. }
  9. }

4. 效果如图

解决SpringBoot @value注解取不到值的问题

5.正确的方法为

解决SpringBoot @value注解取不到值的问题

总结:

从上面方法得知,第一种方法没有获取到值是因为没有在springapplication容器里获取student的bean,因为在实体类加上了@comment注解,这个注解就是把student变成一个bean,才能读取到,不能new 一个对象调用

SpringBoot @Value注解设置默认值

默认值的设置:

解决SpringBoot @value注解取不到值的问题

符合SpEL表达式

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/qq_42274641/article/details/83107807

延伸 · 阅读

精彩推荐