最佳答案
我想在我的控制器中使用带注释的原型 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");
}
}