是否在spring mvc中为每个请求创建了一个新的bean对象?

时间:2013-06-12 14:03:06

标签: java spring spring-mvc

我无法理解在spring mvc中只使用调度程序servlet创建了一个bean对象,或者每次请求都创建了一个新对象?

控制器代码: -

在代码中,我在LoginBean对象中设置数据,并在方法abc中的modelandview对象中设置它。

然后在jsp中我没有为usename输入任何值,在这种情况下,当我提交表单并且当调用处理程序方法(initform)时,我正在尝试打印相同的lb.getusername,这不会让我失望任何价值。 无法理解这个概念。

@Controller
public class LoginController{
ModelAndView mv=null;
EmployeeBean e=new EmployeeBean();
AutoBean autobean;
@Autowired
public LoginController(AutoBean autobean){
    System.out.println("autobean");

    this.autobean=autobean;
}
    @RequestMapping(value="/login")
    public ModelAndView abc(){

        System.out.println("here");
        System.out.println("here1");
        LoginBean lb=new LoginBean();
        lb.setUsename("ankita");//setting value
        return new ModelAndView("login","loginbean",lb);
    }

    @RequestMapping(value="/abc1",method=RequestMethod.POST)
    public ModelAndView initform(@ModelAttribute("loginbean")LoginBean      lb,BindingResult result,Model model){
        System.out.println("*****"+result.getErrorCount());
        System.out.println("hello");
        autobean.setName("yayme");
        System.out.println(autobean.getName());
        model.addAttribute("autobean", autobean);
        System.out.println("username"+lb.getUsename());// query??
        if(lb.getPassword().equals("ankita"))
        /*{
            mv=new ModelAndView();
            e.setId("1001");
            e.setName("ankita");
            mv.addObject("employee", e);
            mv.addObject("emp", new Emp());

            mv.setViewName("success");
            return mv;
        }*/
        return new ModelAndView("success","emp",new Emp());
        else
            return new ModelAndView("fail","lb1",lb);
    }

的login.jsp

<form:form action="abc1" commandName="loginbean">
username:<form:input path="usename" />
password:<form:password path="password"/>
<input type="submit"/>
</form:form>

请建议?

1 个答案:

答案 0 :(得分:5)

Spring的应用程序上下文 bean IoC容器,负责管理从实例化到销毁的bean生命周期)包含bean定义。这些定义包含所谓的scope。此范围可以具有以下值:

  • singleton - 在应用程序生命周期内只创建了一个bean实例
  • prototype - 每当有人要求(applicationContext.getBean(...))为此bean创建一个新实例时

你也可以有一些特殊的范围:

  • request - bean生命周期绑定到HTTP请求
  • session - bean生命周期绑定到HTTP会话

您甚至可以创建自己的范围。 Bean的默认范围为singleton 。因此,如果您没有另外指定,则bean为singleton(每个应用程序的单个实例)。


如果您使用component-scan搜索注释为@Component的类(如注释(例如@Controller)),则这些类将自动注册为应用程序上下文中的bean定义。默认范围也适用于它们。

如果要更改这些自动注册bean的范围,则必须使用@Scope注释。如果您对如何使用它感兴趣,请检查它的JavaDoc。


TL; DR 您的LoginControllersingleton