Reputation: 81
My Spring boot app runs but says failed to start and it says the following:
Field userDetailsService in com.example.security.WebSecurityConfiguration required a bean of type 'com.example.security.UserDetailsServiceImpl' that could not be found.
The injection point has the following annotations:
@org.springframework.beans.factory.annotation.Autowired(required=true)
Consider defining a bean of type 'com.example.security.UserDetailsServiceImpl' in your configuration.
I have tried adding @Bean
and @Service
annotations in my UserDetailsServiceImpl class and adding the beanutils dependency in the pom.xml file but it still issues the same message of failing to start.
My UserDetailsServiceImpl
class:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.example.domain.User;
import com.example.repository.UserRepository;
public class UserDetailsServiceImpl implements UserDetailsService{
@Autowired
private UserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepo.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User with username: " + username + " not found");
}
return new CustomSpringUser (user);
}
}
It should say something like successfully ran Spring-Boot app.
Upvotes: 3
Views: 7206
Reputation: 44398
BeanUtils won't help you in this case. The UserDetailsService
cannot be properly injected since it is not registered as a bean, which only the following annotations are suitable to do so:
@Repository
, @Service
, @Controller
or @Component
where I highly recommend @Service
in this case.The annotation must be placed on the class level since you want to inject its instance. Of course, the class must be an implementation of the interface that is the implementation injected in.
@Service // must be on the class level
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// method implementation...
}
}
On top of that, I recommend you to read the following links:
Upvotes: 5