@Scope("prototype") bean scope not creating new bean

时间:2021-07-20
本文章向大家介绍@Scope("prototype") bean scope not creating new bean,主要包括@Scope("prototype") bean scope not creating new bean使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

代码

@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;
    }
}
@Component
@Scope("prototype")
public class LoginAction {

  private int counter;

  public LoginAction(){
    System.out.println(" counter is:" + counter);
  }
  public String getStr() {
    return " counter is:"+(++counter);
  }
}

问题

为什么将LoginAction 配置为 @Scope("prototype"),在 HomeController 调用的时候并没有每次new一个实例出来?

原因

其实很简单,LoginAction 是 @Scope("prototype"), 但 HomeController 并不是(默认是单例)。
@Scope("prototype") 意思是每次你向spring要一个instance的时候,它都会为你new一个。

解决

在本例中,如果每次调用都需要一个new一个instance的话,可以使用getBean方法。

context.getBean(..)

或者Spring 2.5之后,可以使用ScopedProxyMode控制

@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS) 

参考

https://stackoverflow.com/questions/7621920/scopeprototype-bean-scope-not-creating-new-bean

原文地址:https://www.cnblogs.com/talentzemin/p/15037138.html