解決SpringBoot @value注解取不到值的問(wèn)題
關(guān)于@value的springapplication容器的問(wèn)題
1.在src/main/resources下創(chuàng)建stu.properties文件
## student.name=Tom student.age=22 student.birthday=1996/01/10 student.sex=true student.hobbies[0]=swimming student.hobbies[1]=basketball student.skills[0]=programming student.skills[1]=test student.address.province=henan student.address.city=zhengzhou
2.創(chuàng)建實(shí)體類(lèi)
package com.fcy.entity;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource({"classpath:stu.properties"})
public class Student {
@Value("${student.name}")
private String name;
@Value("${student.age}")
private int age;
@Value("${student.sex}")
private boolean sex;
@Value("${student.birthday}")
private Date birthday;
private String[] hobbies;
private List<String> skills;
private Map<String, Object> address;
//省略getter和setter方法
}
3.錯(cuò)誤的方法
@RestController
public class StudentController {
@RequestMapping("/getStu")
public Student getStu() {
Student stu=new Student();
System.out.println(stu);
return stu;
}
}
4. 效果如圖

5.正確的方法為

總結(jié):
從上面方法得知,第一種方法沒(méi)有獲取到值是因?yàn)闆](méi)有在springapplication容器里獲取student的bean,因?yàn)樵趯?shí)體類(lèi)加上了@comment注解,這個(gè)注解就是把student變成一個(gè)bean,才能讀取到,不能new 一個(gè)對(duì)象調(diào)用
SpringBoot @Value注解設(shè)置默認(rèn)值
默認(rèn)值的設(shè)置:

符合SpEL表達(dá)式
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring+SpringMVC+MyBatis整合實(shí)戰(zhàn)(SSM框架)
框架整合難不難?難!東西多,配置文件復(fù)雜不好記憶,本文就來(lái)介紹一下Spring+SpringMVC+MyBatis整合實(shí)戰(zhàn),具有一定的參考價(jià)值,感興趣的可以了解一下2021-08-08
java中處理json各種各樣的轉(zhuǎn)換方法(推薦)
下面小編就為大家分享一篇java中處理json各種各樣的轉(zhuǎn)換方法小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2017-11-11
springboot 實(shí)現(xiàn)長(zhǎng)鏈接轉(zhuǎn)短鏈接的示例代碼
短鏈接服務(wù)通過(guò)將長(zhǎng)URL轉(zhuǎn)換成6位短碼,并存儲(chǔ)長(zhǎng)短鏈接對(duì)應(yīng)關(guān)系到數(shù)據(jù)庫(kù)中,用戶(hù)訪問(wèn)短鏈接時(shí),系統(tǒng)通過(guò)查詢(xún)數(shù)據(jù)庫(kù)并重定向到原始URL,實(shí)現(xiàn)快速訪問(wèn),本文就來(lái)介紹一下如何使用,感興趣的可以了解一下2024-09-09
Java通過(guò)SMS短信平臺(tái)實(shí)現(xiàn)發(fā)短信功能 含多語(yǔ)言
這篇文章主要為大家詳細(xì)介紹了Java通過(guò)SMS短信平臺(tái)實(shí)現(xiàn)發(fā)短信功能的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-07-07
關(guān)于SpringBoot使用Redis空指針的問(wèn)題(不能成功注入的問(wèn)題)
這篇文章主要介紹了關(guān)于SpringBoot使用Redis空指針的問(wèn)題(不能成功注入的問(wèn)題),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11

