Case 1:
@Scope(‘Session’)
public class Employee{
//..
}
@Controller
public class EmployeeController {
@Autowired
private Employee employee;
//..
}
}
Case 2:
@Controller
@SessionAttributes("employee")
public class EmployeeController {
@ModelAttribute
public void addEmployee(){
//..
}
}
Is Case1 and Case 2 same?
Both method create a session attribute.
When using @Scope(‘Session’)
spring determines the name, and the bean do not automatically populates the model of any controller. It is a normal bean that can be autowired. But if you want the current value (the one in current session) for autowiring in a singleton bean, you must use a scope-proxy.
When using @SessionAttributes(‘employee’)
you declare that the model attribute employee
will live in session. If any method of the controller needs to initialize the attribute after a submit, spring will look in session for a version of the attribute. But it cannot be autowired in another bean.
So while the 2 methods apparently gives same result : employee
in session, they correspond to different use cases.
@SessionAttributes
spring annotation declares session attributes
.
This will typically list the names of model attributes which should be transparently stored in the session, serving as form-backing beans between subsequent requests. So it is limited to session only
While @Scope
: Specifies the scope to use for the annotated component/bean. Its attributes can be SINGLETON,PROTOYPE,SESSION,REQUEST
. where the default scope is SINGLETON