简体   繁体   English

弹簧自动接线用户

[英]Spring autowired user

I have an authentication service, and a module for the clients, which can be included to retrieve the authenticated user and verify the token. 我有一个身份验证服务,以及一个用于客户端的模块,可以包括这些模块来检索经过身份验证的用户并验证令牌。

What I want to achieve is to be able to do this: @Autowired MyUser user to retrieve the correct user (request scope). 我想要实现的是能够做到这一点: @Autowired MyUser user以检索正确的用户(请求范围)。

What I've done: 我所做的:

In the separate module that the clients can include: 在单独的模块中,客户端可以包括:

@Configuration
public class MyUserHolder {
    @Bean
    @Scope(value="request", proxyMode= ScopedProxyMode.TARGET_CLASS)
    public MyUser getMyUser() {
        return (MyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}

And in the client: 在客户端中:

@Autowired MyUser user

There are no annotations on the MyUser class (is this correct?) MyUser类上没有注释(对吗?)

The error I get is: 我得到的错误是:

org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [...MyUser] found for dependency [...MyUser]:
expected at least 1 bean which qualifies as autowire candidate for this dependency. 

I'm not sure if the problem comes from the fact that the object and annotations are in another module (included jar), or if the annotations are just incomplete... It feels like that MyUserHolder is not correctly available in the spring-context 我不确定问题是否来自对象和注释是否在另一个模块(包含的jar)中,或者注释是否不完整...感觉像MyUserHolder在spring-context中无法正确使用

<context:component-scan base-package="com.org.package1,com.org.package2" />

Make sure package includes the class in which bean not found exception occurs. 确保包中包含未找到bean异常的类。 You can use multiple package scan by separating it with `comma (,) 您可以使用多个软件包扫描,方法是使用逗号分隔(,)

Spring will check automatically registered bean ( annotations )inside the package defined in component scan . Spring将在component scan定义的包内检查自动注册的bean( annotations )。

If you want to get current user anywhere you want, I would recommend my approach. 如果您想在任何地方获得当前用户,我建议使用我的方法。
I'v created UserUtil class. 我创建了UserUtil类。
you get null when user is not authenticated. 用户未通过身份验证时,您将获得null。

public static YourUserPrincipalDto getCurrentUser(){
    try {
        return (YourUserPrincipalDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    } catch (Exception e) {
        return null;
    }
}

Generally this issue occurs when Spring can't find bean to autowire, which means before autowiring, a respective bean needs to be created. 通常,当Spring找不到要自动装配的bean时,就会发生此问题,这意味着在自动装配之前,需要创建一个相应的bean。 By making sure that application is scanning (component scan) MyUserHolder class before auto-wiring MyUser in client will resolve such issues. 通过在自动将MyUser连接到客户端之前,确保应用程序正在扫描(组件扫描)MyUserHolder类,可以解决此类问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM