【发布时间】:2018-09-29 16:30:50
【问题描述】:
在我的 Spring Boot 应用程序中,我有以下两个类:
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// TODO re-enable csrf after dev is done
.csrf()
.disable()
// we must specify ordering for our custom filter, otherwise it
// doesn't work
.addFilterAfter(jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class)
// we don't need Session, as we are using jwt instead. Sessions
// are harder to scale and manage
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
和:
@Component
public class JwtAuthenticationFilter extends
AbstractAuthenticationProcessingFilter {
/*
* we must set authentication manager for our custom filter, otherwise it
* errors out
*/
@Override
@Autowired
public void setAuthenticationManager(
AuthenticationManager authenticationManager) {
super.setAuthenticationManager(authenticationManager);
}
}
JwtAuthenticationFilter 通过其setAuthenticationManager 方法依赖于AuthenticationManager bean,但是该bean 是在AppSecurityConfig 中创建的,其中JwtAuthenticationFilter 自动连接。这整个事情创建了一个循环依赖。
我应该如何解决这个问题?
【问题讨论】:
-
它会阻止上下文完全初始化吗?恕我直言,这里涉及 2 种不同类型的依赖项:一种 static 依赖项:您的两个类都依赖于 AuthenticationManager。而 AppSecurityConfig 依赖于 JwtAuthenticationFilter。到目前为止没有任何循环。还有一个 dynamic 依赖,其中 JwtAuthenticationFilter 依赖 AppSecurityConfig 进行运行时初始化。
-
从代码 sn-p 中也不清楚为什么需要在 AppSecurityConfig 中使用 JwtAuthenticationFilter。我会尝试删除这种依赖关系。
-
在 Eclipse 中运行时我没有收到此错误,但是当我使用
sudo ./gradlew build --refresh-dependencies在终端中构建应用程序并刷新其 gradle 依赖项时出现错误:java.lang.IllegalStateException: Failed to load ApplicationContext -
我更新了代码以显示为什么我需要
JWTAuthenticationFilterinAppSecurityConfig -
如果我错了,请纠正我,
JWTAuthenticationFilter中需要的AuthenticationManager在AppSecurityConfig中初始化,AppSecurityConfig已连接JWTAuthenticationFilter。这不形成一个循环依赖?