我正在尝试使用 spring 社交通信 Controller 实现与服务提供商的连接,如 Spring Social reference doc here 中所述.
初始化时,以下服务找不到 currentUser bean。我得到异常
`Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dynamease.serviceproviders.user.User com.dynamease.serviceproviders.SPResolver.currentUser; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.dynamease.serviceproviders.user.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
初始化以下服务时会发生这种情况:
@Service
public class SPResolver {
public SPResolver() {
}
@Autowired
private User currentUser;
@Autowired
private ConnectionRepository connectionRepository;
public void connectUser(String id) {
currentUser.setId(id);
}
public void disconnectUser() {
this.currentUser = null;
}
这里是配置相关的配置文件部分
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public User currentUser() {
return new User(null);
}
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
String id = currentUser().getId();
if (id == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return usersConnectionRepository().createConnectionRepository(id);
}
我怀疑对 bean 定义使用“新用户”可能是原因,也是为什么在 spring 示例中他们使用静态 SecurityContext 类并将用户信息封装在 threadlocal 中但在文档中没有找到任何令人信服的信息的原因关于它。 预先感谢您的帮助。
最佳答案
感谢Sotirios的回答和意见交流,我仔细阅读了Spring引用文档的5.5和9.6节,发现了问题:
如果您确保:
- 您使用某种 AOP 代理机制,以便在最初创建 @Service 并且作用域 bean 不存在时,将创建一个代理,然后在程序执行期间正确引用作用域 bean。这就是我在初始代码中通过 currentUser bean 创建中的
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
行实际执行的操作。 - 作用域 bean 需要在
@Service
中通过接口(interface)引用,而不是直接使用 Java 类,我没有为User
类这样做。实际上,我为 ConnectionRepository Bean 使用的复制粘贴示例正在运行,因为 ConnectionRepository 是一个接口(interface)。
这是工作配置类代码:
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public CurrentUserContext currentUser() {
return new CurrentUserContextImpl();
}
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
String id = currentUser().getId();
if (id == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return usersConnectionRepository().createConnectionRepository(id);
}
和@Service 声明:
@Service
public class SPResolver {
public SPResolver() {
}
@Autowired
private CurrentUserContext currentUser;
@Autowired
private ConnectionRepository connectionRepository;
关于java - Autowiring @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES) 对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20924824/