Spring: new() operator and autowired together
jakarta-ee, spring, spring-mvc
Solution
By using dependency injection does not mean that the use of `new` operator is automatically prohibited throughout your code. It's just different approaches applied to different requirements.
A web application in spring is composed of a number of collaborating beans that are instantiated by the framework and (unless overriding the default scope) are singletons. This means that they must not preserve any state since they are shared across all requests (threads). In other words if you autowire the User object (or any other model attribute), it is created on application context initialization and the same instance is given to any user request. This also means that if a request modifies the object, other requests will see the modification as well. Needless to say this is erroneous behavior in multithreaded applications because your User object (or other model attribute) belongs to the request, so it must have the very narrow scope of a method invocation, or session at most.
You can also have spring create beans with different scopes for you, but for a simple scenario of a model attribute initialization, the `new` operator is sufficient. See the following documentation if interested in bean scopes : Bean scopes
So in your use case, the second method is totally wrong. But you can also delegate the creation of your model attributes to spring if they are used as command objects (i.e. if you want to bind request parameters to them). Just add it in the method signature (with or without the modelattribute annotation).
So you may also write the above code as
@RequestMapping(method=RequestMethod.GET)
public String create(@ModelAttribute User user){
return "index";
}
see also : Supported method argument types
Problem
If I use Spring, which of these two methods is more correct. Can I use the new() operator even if I use dipendency injection?.Can I mix both? I would like to have some clarification on these concepts. Thanks First method: ``` @RequestMapping(method=RequestMethod.GET) public String create(Model model){ model.addAttribute(new User()); return "index"; } ``` Second Method: ``` @Autowired User user; @RequestMapping(method=RequestMethod.GET) public String create(Model model){ model.addAttribute(user); return "index"; } ```