春季:了解@SessionAttributes与@Scope('session')之间的区别 [英] Spring: Understanding on difference between @SessionAttributes vs @Scope('session')
问题描述
情况1:
@Scope(‘Session’)
public class Employee{
//..
}
@Controller
public class EmployeeController {
@Autowired
private Employee employee;
//..
}
}
情况2:
@Controller
@SessionAttributes("employee")
public class EmployeeController {
@ModelAttribute
public void addEmployee(){
//..
}
}
案例1和案例2是否相同?
Is Case1 and Case 2 same?
推荐答案
这两个方法都创建了会话属性.
Both method create a session attribute.
使用@Scope(‘Session’)
时,spring会确定名称,并且bean不会自动填充任何控制器的模型.它是可以自动装配的普通bean.但是,如果要在单例bean中自动装配当前值(当前会话中的那个),则必须使用scope-proxy.
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.
使用@SessionAttributes(‘employee’)
时,您声明模型属性employee
将存在于会话中.如果控制器的任何方法需要在提交后初始化属性,则spring将在会话中查找该属性的版本.但是它不能自动连接到另一个bean中.
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.
因此,虽然这两种方法显然给出了相同的结果:employee
在会话中,但它们对应于不同的用例.
So while the 2 methods apparently gives same result : employee
in session, they correspond to different use cases.
这篇关于春季:了解@SessionAttributes与@Scope('session')之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!