I've been trying to encrypt passwords following the tutorial found here https://www.baeldung.com/spring-security-registration-password-encoding-bcrypt. I created my bean, but had the quite common problem that my autowired fields never got injected. I have tried to sort this problem now for quite a while, following various advice on here such as the following resource Why is my Spring @Autowired field null? but none of the help seems to be working, and I'm really not too sure where I am going wrong. I even tried putting the beans in the xml, although I couldn't get this to work either.
Here is my code so far:
User class, where the autowired field is null
@Service
@Configurable
public class User {
@Id
private UUID id;
private long alias;
private String username;
private String password;
@Autowired
private PasswordEncoder passwordEncoder;
Config class where the bean is getting set up:
@Configuration
public class Config {
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
I'm quite new to spring so I'm sorry if it's a really glaring fix, I just don't know how else to try make it work. Thank you for any help.
Updated code with qualifiers:
config class:
@Configuration
public class Config {
@Bean("bCryptPasswordEncoder")
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
user class:
@Autowired
@Qualifier("bCryptPasswordEncoder")
private PasswordEncoder passwordEncoder;
How the user is being instantiated:
@PostMapping("/users")
public String newUser(@RequestBody User newUser) {
if (repository.existsByUsername(newUser.getUsername())){
return new UserAlreadyExistsException(newUser.getUsername()).getMessage(newUser.getUsername(), repository);
}
User u = new User(getAlias(repository), newUser.getUsername(), newUser.getPassword());
repository.save(u);
return "{\"message\" : \"user\", \"user\" : " + u.toString() + "}";
}