问题描述
我想在我的控制器中使用一个带注释的原型 bean.但是 spring 正在创建一个单例 bean.这是代码:
I want to use a annotated prototype bean in my controller. But spring is creating a singleton bean instead. Here is the code for that:
@Component
@Scope("prototype")
public class LoginAction {
private int counter;
public LoginAction(){
System.out.println(" counter is:" + counter);
}
public String getStr() {
return " counter is:"+(++counter);
}
}
控制器代码:
@Controller
public class HomeController {
@Autowired
private LoginAction loginAction;
@RequestMapping(value="/view", method=RequestMethod.GET)
public ModelAndView display(HttpServletRequest req){
ModelAndView mav = new ModelAndView("home");
mav.addObject("loginAction", loginAction);
return mav;
}
public void setLoginAction(LoginAction loginAction) {
this.loginAction = loginAction;
}
public LoginAction getLoginAction() {
return loginAction;
}
}
速度模板:
LoginAction counter: ${loginAction.str}
Spring config.xml
已启用组件扫描:
Spring config.xml
has component scanning enabled:
<context:annotation-config />
<context:component-scan base-package="com.springheat" />
<mvc:annotation-driven />
我每次都得到一个递增的计数.想不通我哪里错了!
I'm getting an incremented count each time. Can't figure out where am I going wrong!
更新
按照 @gkamal 的建议,我制作了 HomeController
webApplicationContext
-知道它解决了问题.
As suggested by @gkamal, I made HomeController
webApplicationContext
-aware and it solved the problem.
更新代码:
@Controller
public class HomeController {
@Autowired
private WebApplicationContext context;
@RequestMapping(value="/view", method=RequestMethod.GET)
public ModelAndView display(HttpServletRequest req){
ModelAndView mav = new ModelAndView("home");
mav.addObject("loginAction", getLoginAction());
return mav;
}
public LoginAction getLoginAction() {
return (LoginAction) context.getBean("loginAction");
}
}
推荐答案
Scope 原型意味着每次你向 spring(getBean 或依赖注入)请求一个实例时,它会创建一个新实例并给出一个引用.
Scope prototype means that every time you ask spring (getBean or dependency injection) for an instance it will create a new instance and give a reference to that.
>
在您的示例中,创建了一个新的 LoginAction 实例并将其注入到您的 HomeController 中.如果您有另一个控制器向其中注入 LoginAction,您将获得不同的实例.
In your example a new instance of LoginAction is created and injected into your HomeController . If you have another controller into which you inject LoginAction you will get a different instance.
如果您希望每次调用都有不同的实例 - 那么您每次都需要调用 getBean - 注入单例 bean 将无法实现这一点.
If you want a different instance for each call - then you need to call getBean each time - injecting into a singleton bean will not achieve that.
这篇关于@Scope(“prototype") bean 作用域不创建新 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!