我的Spring启动应用程序运行,但说无法启动,它说:
com.example.security.WebSecurityConfiguration中的字段userDetailsService需要一个无法找到的类型为“com.example.security.UserDetailsServiceImpl”的bean。
注入点具有以下注释:
@org.springframework.beans.factory.annotation.Autowired(required=true)
考虑在配置中定义类型为“com.example.security.UserDetailsServiceImpl”的bean。
我尝试在我的UserDetailsServiceImpl类中添加@Bean
和@Service
注释,并在pom.xml文件中添加beanutils依赖项,但它仍然发出无法启动的相同消息。
我的UserDetailsServiceImpl
课程:
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);
}
}
应该说成功运行Spring-Boot应用程序。
在这种情况下,BeanUtils不会帮助你。 UserDetailsService
无法正确注入,因为它未注册为bean,只有以下注释适合这样做:
@Repository
,@Service
,@Controller
或@Component
在这种情况下我强烈推荐@Service
。由于您要注入其实例,因此注释必须放在类级别上。当然,该类必须是注入实现的接口的实现。
@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...
}
}
最重要的是,我建议您阅读以下链接:
将@Service注释放在UserDetailsServiceImpl类上。