弹簧自动布线“忘记”依赖关系

我想玩一下不同类型的bean示波器。所以我写了一个测试环境,它应该生成一个随机数,这样我就可以看到一个bean是否发生了变化。我的测试设置不起作用,我无法解释我发现的内容。


我正在使用Spring Boot 2.13和Spring Framework 5.15。


以下设置:


主类:


package domain.webcreator;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public 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;


@Configuration

public 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;


@Controller

public class IndexController {

    @GetMapping("/")

    @ResponseBody

    @Autowired

    public String indexAction(Scoper scoper) {

        return String.valueOf(scoper.getNumber(50));

    }

}

我的问题是,我在调用 scoper.getNumber(50) 时得到了一个 NPE。这很奇怪,因为在调试时,会生成一个 Random Bean 并将其传递给作用域器构造函数。稍后,在控制器中,rand 属性为 null。


慕虎7371278
浏览 71回答 1
1回答

杨__羊羊

你试图应用一个随机的方法,这不是Spring的工作方式。控制器方法参数用于特定于该HTTP请求的信息,而不是一般依赖项,因此Spring正在尝试创建一个与请求关联的新参数 - 但它在请求中没有任何要填写的传入值。@AutowiredScoper相反,请在构造函数中传递您的构造函数。Scoper@RestControllerpublic 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java