4

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?

1
  • My understanding is Case 1 and case 2 does the same. We use @Scope(Session) to apply it to complete class. Hence I may use @Scope(‘Session’) at Controller level and make the controller and its attributes(may be POJO or primitive java variables) session scoped. When we use @SessionAttribute(‘model’) it limits to a particular attribute. Please share you understanding. Commented Aug 4, 2014 at 15:02

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you I think you are suggesting this: <!-- an HTTP Session-scoped bean exposed as a proxy --> <bean id="employee" class="com.test.Employee" scope="session"> <!-- this next element effects the proxying of the surrounding bean --> <aop:scoped-proxy/> </bean> Controller public class EmployeeController { Autowired private Employee employee; RequestMapping("/viewEmployeeDetails") public ModelAndView viewEmployeeDetails() { // now just use the employee } }
0

@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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.