我想玩一下不同类型的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。
杨__羊羊
相关分类