我想玩一下不同類型的bean示波器。所以我寫了一個測試環境,它應該生成一個隨機數,這樣我就可以看到一個bean是否發生了變化。我的測試設置不起作用,我無法解釋我發現的內容。我正在使用Spring Boot 2.13和Spring Framework 5.15。以下設置:主類:package domain.webcreator;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class WebcreatorApplication { public static void main(String[] args) { SpringApplication.run(WebcreatorApplication.class, args); }}豆類:package domain.webcreator;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.util.Random;@Configurationpublic class Beans { @Bean public Random randomGenerator() { return new Random(); }}作用域器類:package domain.webcreator;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Service;import java.util.Random;@Service@Scope("singleton")public class Scoper { private Random rand; public Scoper(Random rand) { this.rand = rand; } public int getNumber(int max) { return rand.nextInt(max); }}索引控制器package domain.webcreator.controller;import domain.webcreator.Scoper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class IndexController { @GetMapping("/") @ResponseBody @Autowired public String indexAction(Scoper scoper) { return String.valueOf(scoper.getNumber(50)); }}我的問題是,我在調用 scoper.getNumber(50) 時得到了一個 NPE。這很奇怪,因為在調試時,會生成一個 Random Bean 并將其傳遞給作用域器構造函數。稍后,在控制器中,rand 屬性為 null。
1 回答

楊__羊羊
TA貢獻1943條經驗 獲得超7個贊
你試圖應用一個隨機的方法,這不是Spring的工作方式??刂破鞣椒▍涤糜谔囟ㄓ谠揌TTP請求的信息,而不是一般依賴項,因此Spring正在嘗試創建一個與請求關聯的新參數 - 但它在請求中沒有任何要填寫的傳入值。@AutowiredScoper
相反,請在構造函數中傳遞您的構造函數。Scoper
@RestController
public class IndexController {
private final Scoper scoper;
public IndexController(Scoper scoper) {
this.scoper = scoper;
}
@GetMapping("/")
public String indexAction(Scoper scoper) {
return String.valueOf(scoper.getNumber(50));
}
}
一些注意事項:
單例作用域是默認值,無需指定它。
@RestController
比重復更可取,除非您有一個混合的控制器類。@ResponseBody
添加回答
舉報
0/150
提交
取消