Spring 如何自动装配会话范围的 bean?
How does Spring autowire session scoped beans?
我目前正在处理会话对象。在服务层中,我正在自动装配会话范围的 bean。我想知道 Spring 是如何做到这一点的?更有趣的是,即使我使用 final 关键字并使用构造函数注入,Spring 仍然能够自动装配对象。
@Service
public class SomeServiceImpl implements SomeService {
private final UserSessionDetails userSessionDetails;
@Autowired
public SomeServiceImpl(final UserSessionDetails userSessionDetails) {
this.userSessionDetails = userSessionDetails;
}
}
我的另一个问题是;在服务层使用会话对象是好习惯吗?或者我可以在 Controller 和 Service 层中自由使用这些对象吗?
你是由构造函数自动装配的,所以在这种情况下使用单词 final
不会改变任何东西。通过将 UserSessionDetails
注释为会话范围的 bean,并将其注入 SomeServiceImpl
spring 生成一个代理。来自您服务的任何调用都被委托给 UserSessionDetails
bean。
I wonder how Spring is able to do this?
SomeServiceImpl
是单例,所以应该在启动时组装。组装一个 bean 意味着向它注入所有必需的依赖项。虽然有些candidates的scope可能和singleton scope不一样,但是还是要提供的。对于这样的 bean,Spring 创建代理。在某些上下文出现之前,代理基本上是一个无意义的包装器。
if I use final keyword and use constructor injection, Spring is still able to autowire the object.
Spring 支持基于构造函数的注入。它检查签名并查找要注入的候选人;字段的修饰符无关紧要。
Is it good practice the using session objects in Service layer? Or am I free to use these objects in Controller and Service layers?
只要该服务是面向 Web 且与会话相关的,您就可以自由地向其注入会话范围的 bean。
我目前正在处理会话对象。在服务层中,我正在自动装配会话范围的 bean。我想知道 Spring 是如何做到这一点的?更有趣的是,即使我使用 final 关键字并使用构造函数注入,Spring 仍然能够自动装配对象。
@Service
public class SomeServiceImpl implements SomeService {
private final UserSessionDetails userSessionDetails;
@Autowired
public SomeServiceImpl(final UserSessionDetails userSessionDetails) {
this.userSessionDetails = userSessionDetails;
}
}
我的另一个问题是;在服务层使用会话对象是好习惯吗?或者我可以在 Controller 和 Service 层中自由使用这些对象吗?
你是由构造函数自动装配的,所以在这种情况下使用单词 final
不会改变任何东西。通过将 UserSessionDetails
注释为会话范围的 bean,并将其注入 SomeServiceImpl
spring 生成一个代理。来自您服务的任何调用都被委托给 UserSessionDetails
bean。
I wonder how Spring is able to do this?
SomeServiceImpl
是单例,所以应该在启动时组装。组装一个 bean 意味着向它注入所有必需的依赖项。虽然有些candidates的scope可能和singleton scope不一样,但是还是要提供的。对于这样的 bean,Spring 创建代理。在某些上下文出现之前,代理基本上是一个无意义的包装器。
if I use final keyword and use constructor injection, Spring is still able to autowire the object.
Spring 支持基于构造函数的注入。它检查签名并查找要注入的候选人;字段的修饰符无关紧要。
Is it good practice the using session objects in Service layer? Or am I free to use these objects in Controller and Service layers?
只要该服务是面向 Web 且与会话相关的,您就可以自由地向其注入会话范围的 bean。