SpringBoot中通过构造函数表示的不满意依赖性
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot中通过构造函数表示的不满意依赖性相关的知识,希望对你有一定的参考价值。
嗨,我的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:CCCintellij_exfoodyfoody-customer-
apiuildclassesjavamainkrcoloosiefoodyapplicationUserService.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配置)
以上是关于SpringBoot中通过构造函数表示的不满意依赖性的主要内容,如果未能解决你的问题,请参考以下文章
为啥我们需要一个默认构造函数来在 C++ 中通过引用传递一个对象?