Spring 循环依赖

标签 spring spring-security

我有以下配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityConfig.class);
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private PasswordEncoder passwordEncoder;

    .....

    @Configuration
    @Order(2)
    public static class MobileApiSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        @Resource
        private UserDetailsService userDetailsService;
        @Resource
        private PasswordEncoder passwordEncoder;
        @Autowired
        private CustomBasicAuthenticationFilter customBasicAuthenticationFilter;
        @Autowired
        private TokenSecurityFilter tokenSecurityFilter;

        protected void configure(AuthenticationManagerBuilder auth) throws Exception {

            auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder);

        }

        protected void configure(HttpSecurity http) throws Exception {
            http
                .addFilter(customBasicAuthenticationFilter)
                .addFilterBefore(tokenSecurityFilter, CustomBasicAuthenticationFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                    .csrf().disable()
                .authorizeRequests()           
                    .antMatchers(Mappings.MOBILE_API + "/**").hasAnyRole(Globals.MOBILE_API_USER_ROLE)
                    .and()
                .exceptionHandling()
                    .authenticationEntryPoint(new CustomBasicAuthenticationEntryPoint())
                    .and()
                .requestCache()
                    .requestCache(new NullRequestCache());
        }

    }

这是我的自定义过滤器:

@Component
public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomBasicAuthenticationFilter.class);
    @Autowired
    private PrincipalRepository principalRepository;
    @Autowired
    private AuthenticationCache authenticationCache;

    @Autowired
    public CustomBasicAuthenticationFilter(AuthenticationManager authenticationManager) {
       super(authenticationManager);
    }

    @Override
    protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
            Authentication authResult) throws IOException {
        Principal principal = principalRepository.findOne(PrincipalPredicates.userNameEquals(authResult.getName()));

        if (principal != null) {
            principal.setLastLoginTime(DateTime.now());
            principalRepository.save(principal);
        } else {
            LOGGER.error("Unable to retrieve user " + authResult.getName());
        }

        authenticationCache.add(authResult, request, response);

        super.onSuccessfulAuthentication(request, response, authResult);
    }
}

但是,当尝试部署到 Tomcat 时,会抛出以下异常:

Error creating bean with name 'customBasicAuthenticationFilter' defined in file [C:\work\...]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.security.authentication.AuthenticationManager]: : No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

我不确定为什么我的过滤器正在寻找 authenticationManager,因为我正在 Autowiring 它。感谢您的帮助。

更新问题:我添加了这段代码来解决 authenticationManager 问题:

@Bean(name="myAuthenticationManager")
           @Override
           public AuthenticationManager authenticationManagerBean() throws Exception {
               return super.authenticationManagerBean();
           }

通过添加以上内容,我能够解决 authenticationManager 问题,但现在我遇到了这个问题:

    org.springframework.beans.factory.BeanCreationException:
 Could not autowire field: private CustomBasicAuthenticationFilter SecurityConfig$MobileApiSecurityConfigurerAdapter.customBasicAuthenticationFilter; 
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'customBasicAuthenticationFilter':
 Requested bean is currently in creation: Is there an unresolvable circular reference?

谢谢

最佳答案

您可以尝试在 MobileApiSecurityConfigurerAdapter 类定义之上添加 @EnableWebSecurity 注释。

关于 Spring 循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049614/

相关文章:

java - 作为 byte[] 发送的字符串内容将其内容转义为查询字符串

java - Intellij 如何使用 spring boot 正确配置 hql。现在我得到 Persistence QL Queries are error-checked

java - 使用 Micrometer 设置 InfluxDB 指标的常见标签

java - Spring-Security-OAuth2 中的 grant_type

java - springboot应用程序启动失败

java - 如何在无状态服务中编写带有可变参数的模板流程?

spring-security - 同一实体的两个存储库,一个已导出,一个未导出

authentication - 使用 Spring Security 进行 flask 用户身份验证

spring-mvc - Spring MVC 4 全局基本 HTTP 身份验证

java - Spring 安全警告 : Class AuthorityUtils is abstract?