我有一个conconller,其定义如下:
@RestController
public class DemoController {
@Autowired
PrototypeBean proto;
@Autowired
SingletonBean single;
@GetMapping("/test")
public String test() {
System.out.println(proto.hashCode() + " "+ single.hashCode());
System.out.println(proto.getCounter());
return "Hello World";
}
}
我已经定义了原型bean如下:
@Component
@Scope(value= ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PrototypeBean {
static int i = 0;
public int getCounter() {
return ++i;
}
}
每次我打http://localhost:8080/test 我得到相同的实例,并且计数器每次都递增。 如何确保每次都获取新实例? 我也想知道为什么即使我已将bean的范围声明为Prototype,也没有获得新实例。
答案 0 :(得分:1)
您已将DemoController
声明为@RestController
,因此它是具有单例作用域的bean。这意味着它仅创建一次,并且PrototypeBean
也仅注入一次。这就是为什么每个请求都具有相同对象的原因。
要查看原型如何工作,您必须将bean注入其他bean。这意味着,拥有两个@Component
,都自动装配PrototypeBean
,PrototypeBean
的实例在这两个实例中会有所不同。
答案 1 :(得分:0)
首先,static
变量与类而不是实例相关联。删除静态变量。同时添加@Lazy
批注。
像这样
@RestController
public class DemoController {
@Autowired
@Lazy
PrototypeBean proto;
@Autowired
SingletonBean single;
@GetMapping("/test")
public String test() {
System.out.println(proto.hashCode() + " "+ single.hashCode());
System.out.println(proto.getCounter());
return "Hello World";
}
}
@Component
@Scope(value= ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PrototypeBean {
int i = 0;
public int getCounter() {
return ++i;
}
}
答案 2 :(得分:0)
您要实现的目标是使用SCOPE_REQUEST(每个http请求的新实例)完成的。
答案 3 :(得分:0)
如果您的目标是每次调用 PrototypeBean
方法时都获得 test()
的新实例,请执行 @Autowired
of BeanFactory beanFactory
,删除 {{ 的全局类字段1}},在方法 PrototypeBean
中,检索 test()
如下:
PrototypeBean