我想在控制器中使用带注释的原型bean。但是春天正在创建一个单例豆。这是该代码:
@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
已启用组件扫描:
<context:annotation-config />
<context:component-scan base-package="com.springheat" />
<mvc:annotation-driven />
我每次都得到递增计数。无法弄清楚我要去哪里错了!
更新资料
按照@gkamal的建议,我做了HomeController
webApplicationContext
可以解决问题。
更新的代码:
@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");
}
}