亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

彈簧自動布線“忘記”依賴關系

彈簧自動布線“忘記”依賴關系

慕虎7371278 2022-08-17 10:58:58
我想玩一下不同類型的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


查看完整回答
反對 回復 2022-08-17
  • 1 回答
  • 0 關注
  • 89 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號