嗨,我的springboot版本是'2.2.4.RELEASE'。我想在构造函数中自动装配2参数。但它不起作用。马比,我认为“ passwordEncoder”有问题...这是'UserService.java'代码。
import kr.co.loosie.foody.domain.User;
import kr.co.loosie.foody.domain.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Optional;
@Service
@Transactional
public class UserService {
private UserRepository userRepository;
private PasswordEncoder passwordEncoder;
@Autowired
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public User registerUser(String email, String name, String password) {
Optional<User> existed = userRepository.findByEmail(email);
if (existed.isPresent()) {
throw new EmailExistedException(email);
}
String encodedPassword = passwordEncoder.encode(password);
User user = User.builder()
.email(email)
.name(name)
.password(encodedPassword)
.level(1L)
.build();
return userRepository.save(user);
}
public User authenticate(String email, String password) {
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new EmailNotExistedException(email));
if (!passwordEncoder.matches(password, user.getPassword())) {
throw new PasswordWrongException();
}
return user;
}
}
错误部分在这里。@Autowiredpublic UserService(UserRepository userRepository,PasswordEncoder passwordEncoder){this.userRepository = userRepository;this.passwordEncoder = passwordEncoder;}
当我仅使用UserReposiotory进行自动连线时,它就可以工作但是我把PasswordEncoder passwordEncoder行放了,这行不通。请给我一些帮助!
这是警告消息
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with
name 'userService' defined in file [D:\CCC\intellij_ex\foody\foody-customer-
api\build\classes\java\main\kr\co\loosie\foody\application\UserService.class]: Unsatisfied dependency
expressed through constructor parameter 1; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
'org.springframework.security.crypto.password.PasswordEncoder' available: expected at least 1 bean
which qualifies as autowire candidate. Dependency annotations: {}
请给我一些帮助!
错误消息显示org.springframework.security.crypto.password.PasswordEncoder
没有bean,这意味着您在任何地方都没有定义它。
您将需要类似的东西:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
在您的配置中(如果通过Java配置)