有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring未自动连接AuthenticationManager

我正在IntelliJ中使用SpringBoot创建一个SpringMVC项目。 我正在使用Spring security对用户进行身份验证。我跟着一个向导找到了here

这是我的SecurityService类:

@Service
public class SecurityService {

    @Autowired
    private AuthenticationManager authenticationManager;

    private UserDetailsService userDetailsService = new UserDetailsServiceImpl();

    public String findLoggedInUsername() {
        Object userDetails = SecurityContextHolder.getContext();
        if (userDetails instanceof UserDetails) {
            return ((UserDetails)userDetails).getUsername();
        }
        return null;
    }

    public void autologin(String username, String password) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if(userDetails.getUsername().equals("NotFound")) {
            return;
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());

        authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        if (usernamePasswordAuthenticationToken.isAuthenticated()) {
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }
    }
}

然后我在securityConfig中定义了这些行。xml:

<authentication-manager alias="authenticationManager">
    <authentication-provider user-service-ref="userDetailsServiceImpl">
        <password-encoder ref="encoder"></password-encoder>
    </authentication-provider>
</authentication-manager>

在IntelliJ中,authenticationManager旁边有一个bean图标,当我单击它时,它会将我指向authenticationManager的bean定义

但是,当我尝试编译时,Spring给了我以下错误:

Field authenticationManager in project.service.SecurityService required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.

  • Bean method 'authenticationManager' not loaded because @ConditionalOnBean (types: org.springframework.security.config.annotation.ObjectPostProcessor; SearchStrategy: all) did not find any beans

为什么Spring找不到bean,而IntelliJ可以?我该如何解决这个问题

顺便说一句,我的大部分配置都是通过Spring引导自动配置完成的。我已经尝试添加@Qualifier(“authenticationManager”),但没有成功


共 (1) 个答案

  1. # 1 楼答案

    我认为component-scan有一个问题。您可以在securityConfig.xml中创建bean SecurityService,如下所示

    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref="userDetailsServiceImpl">
            <password-encoder ref="encoder"></password-encoder>
        </authentication-provider>
    </authentication-manager>
    
    <bean id="securityService" class="SecurityService" />