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

我无法理解在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的

 
username: password:

请指教?

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

  • singleton – 在应用程序生命周期中只创建一个bean实例
  • prototype – 每次有人向此bean请求( applicationContext.getBean(...) )时都会创建一个新实例

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

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

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


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

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


TL; DR您的LoginControllersingleton