我正在學習如何使用 Springboot 創建一個 RESTful API,并且@Value 標簽不是從 application.properties 注入值,也不是注入標簽本身中指定的值。我的專案結構如下:
- api
- 配置
- 控制器
- 模型
- 服務
- SpringApplication.java
- 資源
- 應用程式屬性
奇怪的是,這種行為似乎只發生在我的“服務”檔案夾中的檔案中。該@Value標簽在位于我的“控制器”檔案夾中的檔案中按預期作業。以下是我正在做的事情的例子:
@Value("${var}")
String variable
“var”在 application.properties 中定義為,var=some_string但變數仍初始化為“null”
@Value("I am directly assigning a value to this variable, but it still comes out null")
String variable
我相信我正在使用正確的匯入:import org.springframework.beans.factory.annotation.Value. 起初我只是認為“服務”檔案夾對 application.properties 所在的目錄是盲目的,但是在嘗試直接注入值之后,我不太確定該怎么想。
編輯
services 檔案夾中的所有類都帶有注釋,僅此@Service而已。下面是這個類的樣子。我選擇省略方法的實作、其他變數和不相關的匯入。對變數進行硬編碼時,代碼/方法都按預期作業。我的重點是@Value 標簽。
package myapi.api.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Value("${var}")
String variable;
public List<Data> getData() {
return new ArrayList<Data>();
}
public void postData() {
}
編輯 2
下面是 APIController 類,存盤在“controllers”檔案夾中。同樣,我選擇省略不相關的方法/匯入/變數。我還想指出,該@Value標簽在此類中按預期作業。
package myapi.api.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import myapi.api.services.MyService;
import lombok.RequiredArgsConstructor;
@RestController
@RequestMapping("api")
@RequiredArgsConstructor
public class APIController {
@Autowired
private final static MyService myService = new MyService();
@GetMapping("/getdata")
public List<Data> getData() {
return myService.getData();
}
}
uj5u.com熱心網友回復:
@Autowired
private final static MyService myService = new MyService();
三個問題:
首先,您不能有new操作員。Spring 控制類實體的生命周期。它會new在后臺呼喚你。洗掉整個新的運算子節。
下一步:你的領域不能是final. 類構建后,Spring 將需要使用代理修改該欄位。洗掉final宣告;
最后:你的領域不能是static. static變數與JVM有一定的生命周期,你需要讓Spring框架來管理你的生命周期。洗掉靜態運算子。
正確的宣告應該是:
@Autowired
private MyService myService;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/498483.html
下一篇:org.springframework.web.servlet.PageNotFoundnoHandlerFound得到這個
