Неудовлетворительная зависимость/ошибка циклической ссылки в конфигурации безопасности Spring BootJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Неудовлетворительная зависимость/ошибка циклической ссылки в конфигурации безопасности Spring Boot

Сообщение Anonymous »

Я работаю над приложением Spring Boot с использованием Spring Security и столкнулся с проблемой внедрения зависимостей в файл AppConfig.java. Приложение не запустится, если я не использую аннотацию @Lazy в конструкторе. Я бы предпочел избегать использования @Lazy, но у меня возникают циклические ошибки ссылок при попытке настроить безопасность без него.
Вот мой текущий AppConfig.java:

Код: Выделить всё

@Configuration
@EnableWebSecurity
public class AppConfig extends WebSecurityConfigurerAdapter {

private final CurrentUserService currentUserService;
private final SessionFilter sessionFilter;
private final PasswordEncoder passwordEncoder;

@Autowired
@Lazy
public AppConfig(CurrentUserService currentUserService, SessionFilter sessionFilter, PasswordEncoder passwordEncoder) {
this.currentUserService = currentUserService;
this.sessionFilter = sessionFilter;
this.passwordEncoder = passwordEncoder;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(currentUserService).passwordEncoder(passwordEncoder);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http = http.cors().and().csrf().disable();

http = http.exceptionHandling().authenticationEntryPoint(
(request, response, authException) -> {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
}
).and();

http.authorizeRequests().antMatchers("/api/login").permitAll().anyRequest().authenticated();

http.addFilterBefore(sessionFilter, UsernamePasswordAuthenticationFilter.class);
}

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

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Проблема:
Если я удалю @Lazy, приложение не запустится и выдаст следующую ошибку:

Код: Выделить всё

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appConfig' defined in file [C:\path\to\AppConfig.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'appConfig': Requested bean is currently in creation: Is there an unresolvable circular reference?
Я попробовал переключиться на внедрение полей, чтобы избежать внедрения конструктора, вот так:

Код: Выделить всё

@Autowired
private CurrentUserService currentUserService;
@Autowired
private SessionFilter sessionFilter;
@Autowired
private PasswordEncoder passwordEncoder;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(currentUserService).passwordEncoder(passwordEncoder);
}
Но я получаю аналогичную ошибку:

Код: Выделить всё

Error creating bean with name 'appConfig': Unsatisfied dependency expressed through field 'passwordEncoder'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'appConfig': Requested bean is currently in creation: Is there an unresolvable circular reference?
Мои вопросы:

Код: Выделить всё

How can I resolve this circular dependency without relying on @Lazy?
Is there a better approach for injecting these dependencies in a Spring Security configuration?
Are there specific patterns or workarounds for avoiding circular references in Spring Boot security setups?
Будем очень признательны за любые советы и идеи!

Подробнее здесь: https://stackoverflow.com/questions/715 ... ity-config
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»