Привет, я разрабатываю приложение Spring Boot (v1.5.18.BUILD-SNAPSHOT), но это не удается, когда я пытаюсь запустить приложение ....
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of constructor in com.eficacia.security.WebSecurity required a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' in your configuration.
Проблема в том, что у меня настроен bean-компонент:
@Configuration
public class AppConfiguration {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
В моем pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
WebSecurity:
@Configuration
@EnableWebSecurity
@ComponentScan({"com.eficacia.security"})
public class WebSecurity extends WebSecurityConfigurerAdapter {
public static final String USER_REGISTRATION_URL = "/v1/user";
private UserDetailsService userDetailsService;
private BCryptPasswordEncoder bCryptPasswordEncoder;
public WebSecurity(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests().antMatchers(HttpMethod.POST, USER_REGISTRATION_URL).permitAll()
.anyRequest().authenticated()
.and().addFilter(new JWTAuthenticationFilter(authenticationManager(), getApplicationContext()))
.addFilter(new JWTAuthorizationFilter(authenticationManager(), getApplicationContext()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
//configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200","http://opusclick.com","https://gateway2.tucompra.com.co"));
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.setAllowedMethods(Arrays.asList("GET","POST","PUT","PATCH","DELETE"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
WebConfigurer:
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
private final ApplicationContext applicationContext;
private final EntityManager entityManager;
@Autowired
public WebMvcConfiguration(ApplicationContext applicationContext, EntityManager entityManager) {
this.applicationContext = applicationContext;
this.entityManager = entityManager;
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().applicationContext(this.applicationContext).build();
argumentResolvers.add(new DTOModelMapper(objectMapper, entityManager));
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
JacksonMapperConfiguration jacksonMapperConfiguration= new JacksonMapperConfiguration();
converters.add(jacksonMapperConfiguration.mappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
}
Мой вопрос очень простой, и поэтому определение класса 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder 'не найдено, если для этого действительно существует класс конфигурации.
Огромное спасибо!




Похоже, вашего класса веб-конфигуратора нет в пакете com.eficacia.security или в одном из его подпакетов.
Переместите WebMvcConfiguration в место внутри пакетов @ComponentScaned.
@AlejoDev Да, переместите его внутрь com.eficacia.security или любого из его подпакетов.
Spring Security сканирует все ваши пакеты при запуске, если ваш класс WebMvcConfiguration вне пакета безопасности, он не распознает по умолчанию.
@AlejoDev А аннотацию @ComponentScan убирать не пробовали?
@AlejoDev Другой вопрос: в каком пакете находится ваш основной файл Application.java (тот, который имеет аннотацию @SpringBootApplication? Есть ли у @SpringBootApplication атрибут scanBasePackages?
@MarkusPscheidt Нет, нет атрибута scanBasePackages
В каком пакете находится основной файл Application.java (тот, который имеет аннотацию @SpringBootApplication)?
Позвольте нам продолжить обсуждение в чате.
com.eficacia - это пакет
Вы создаете bean-компонент типа PasswordEncoder и пытаетесь автоматически подключить BCryptPasswordEncoder
@Configuration
public class AppConfiguration {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Измените это:
частный BCryptPasswordEncoder bCryptPasswordEncoder;
public WebSecurity(UserDetailsService userDetailsService,
BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
к этому : частный PasswordEncoder passwordEncoder;
public WebSecurity(UserDetailsService userDetailsService,
PasswordEncoder passwordEncoder ) {
this.userDetailsService = userDetailsService;
this.passwordEncoder = PasswordEncoder ;
}
Spring could not found the BcryptPasswordEncoder type as you are returning PasswordEncoder
@AlejoDev Обновленный ответ
Здравствуйте, я очень признателен за вашу помощь, если я попробовал, но это не сработало, я нашел очень простой способ, я просто инициализировал объект вручную, используя зарезервированное слово new
@AlejoDev, не могли бы вы показать образец где не заработало?)
Хорошо, вы имеете в виду, что вы перемещаете класс WebMvcConfiguration внутри пакета com.eficacia.security?