Я создал bean-компонент типа PasswordEncoder, но мое приложение Springboot все равно показывает мне, что у меня нет такоJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Я создал bean-компонент типа PasswordEncoder, но мое приложение Springboot все равно показывает мне, что у меня нет тако

Сообщение Anonymous »

Я работаю над приложением весенней загрузки. где я создал bean-компонент типа PasswordEncoder, но когда я запускаю код, он показывает следующую ошибку:
Описание:

Параметр 1 конструктора в
com.example.FintechBackend.service.UserService
требовал bean-компонент типа
'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder'
который не удалось найти.
Действие:
Рассмотрите возможность определения bean-компонента типа
'org.springframework.security.crypto.bcrypt .BCryptPasswordEncoder' в
вашей конфигурации.

Хотя я уже объявил компонент в файле конфигурации, но все равно получаю эту ошибку. Я не понимаю, как решить эту проблему.
Мои занятия приведены ниже

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

    import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) {

try {
return http
.authorizeHttpRequests(authCustomizer -> authCustomizer
.requestMatchers(HttpMethod.POST,
"/api/users/register", "/api/users/login").permitAll()
.requestMatchers(HttpMethod.GET, "/api/users/{id}").hasRole("USER")
.requestMatchers(HttpMethod.PUT, "/api/users/{id}").hasRole("USER")
.requestMatchers(HttpMethod.DELETE, "/api/users/{id}").hasRole("USER")
.requestMatchers(HttpMethod.POST, "/api/transactions").hasRole("USER")
.requestMatchers(HttpMethod.GET, "/api/transactions/{id}").hasRole("USER")
.requestMatchers(HttpMethod.PUT, "/api/transactions/{id}").hasRole("USER")
.requestMatchers(HttpMethod.DELETE, "/api/transactions/{id}").hasRole("USER")
)
.build();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
BCryptPasswordEncoder, созданный в классе конфигурации, используется в Userservice, код которого следующий:

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

    import com.example.FintechBackendDeveloperAssignment.DTO.UserRegistrationDTO;
import com.example.FintechBackendDeveloperAssignment.model.User;
import com.example.FintechBackendDeveloperAssignment.repository.UserRepository;
import org.slf4j.Logger;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
private final UserRepository userRepository;
private final BCryptPasswordEncoder passwordEncoder;
private final Logger logger;

public UserService(UserRepository userRepository, BCryptPasswordEncoder passwordEncoder, Logger logger) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.logger = logger;
}

public User registerUser(UserRegistrationDTO registrationDTO) {
User existingUser = userRepository.findByEmail(registrationDTO.getEmail());
if (existingUser != null) {
throw new RuntimeException("Email already exists");
}

User user = new User();
user.setName(registrationDTO.getName());
user.setEmail(registrationDTO.getEmail());
user.setRole("USER");
user.setPassword(passwordEncoder.encode(registrationDTO.getPassword()));
userRepository.save(user);

logger.info("User registered: "  + user.getEmail());

return user;
}

public User loginUser(String email, String password) {
User user = userRepository.findByEmail(email);
if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
throw new RuntimeException("Invalid email or password");
}

logger.info("User logged in: " + user.getEmail());

return user;
}
}
Мы создаем объект этого пользовательского сервиса в нашем контроллере, и вот место, откуда он выдает ошибку

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

import com.example.FintechBackendDeveloperAssignment.DTO.UserRegistrationDTO;
import com.example.FintechBackendDeveloperAssignment.model.Transaction;
import com.example.FintechBackendDeveloperAssignment.model.User;
import com.example.FintechBackendDeveloperAssignment.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;

public UserController(UserService userService) {
this.userService = userService;
}

@Tag(name = "post", description = "Post methods of user APIs")
@Operation(summary = "Register User",
description = "This APi is use to register new user in system")
@ApiResponses({
@ApiResponse(responseCode = "200", content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = User.class)) }),
@ApiResponse(responseCode = "404", description = "User not created",
content = @Content) })
@PostMapping("/register")
public ResponseEntity registerUser(@Valid @RequestBody UserRegistrationDTO registrationDTO, BindingResult result) {
if (result.hasErrors()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Validation errors");
}

try {
User user = userService.registerUser(registrationDTO);
return ResponseEntity.status(HttpStatus.CREATED).body(user);
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}

@Operation(summary = "Login User",
description = "This API is use to Login user in system")
@ApiResponses({
@ApiResponse(responseCode = "200", content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = User.class)) }),
@ApiResponse(responseCode = "404", description = "User not LoggedIn",
content = @Content) })
@Tag(name = "post", description = "Post methods of user APIs")
@PostMapping("/login")
public ResponseEntity loginUser(@RequestParam String email, @RequestParam String password) {
try {
User user = userService.loginUser(email, password);
return ResponseEntity.ok(user);
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
}
}
}
Ниже приведена структура моего кода.
Изображение


Подробнее здесь: https://stackoverflow.com/questions/783 ... app-is-sho
Ответить

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

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

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

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

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