我的 Spring boot 应用程序运行,但显示无法启动,并显示以下内容:
Field userDetailsService in com.example.security.WebSecurityConfiguration required a bean of type 'com.example.security.UserDetailsServiceImpl' that could not be found.
注入(inject)点有以下注释:
@org.springframework.beans.factory.annotation.Autowired(required=true)
Consider defining a bean of type 'com.example.security.UserDetailsServiceImpl' in your configuration.
我尝试在 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
无法正确注入(inject),因为它没有注册为 Bean,只有以下注解适合这样做:
@Repository
、@Service
、@Controller
或@Component
,其中我强烈推荐@在本例中为服务
。
注释必须放置在类级别,因为您想要注入(inject)其实例。当然,该类必须是接口(interface)的实现,该接口(interface)是注入(inject)的实现。
@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...
}
}
最重要的是,我建议您阅读以下链接:
- 关于依赖注入(inject),Spring 位于 Baeldung's website .
- 关于组件扫描和组件类型,位于 JavaCodeGeeks和 What's the difference between @Component, @Repository & @Service annotations in Spring?
- 关于构造函数注入(inject)相对于字段一的优点,请参见 Field Dependency Injection Considered Harmful和 What exactly is Field Injection and how to avoid it?
关于java - 如何修复 Spring Boot 中的 "Application failed to start"并要求定义 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55752590/