java - 如何修复 Spring Boot 中的 "Application failed to start"并要求定义 bean

标签 java spring spring-boot spring-security dependency-injection

我的 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.

我尝试在 UserDetailsS​​erviceImpl 类中添加 @Bean@Service 注释,并在 pom.xml 文件中添加 beanutils 依赖项,但它仍然发出相同的消息无法启动。

我的UserDetailsS​​erviceImpl类:

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 不会帮助你。 UserDetailsS​​ervice 无法正确注入(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...
    }
}

最重要的是,我建议您阅读以下链接:

关于java - 如何修复 Spring Boot 中的 "Application failed to start"并要求定义 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55752590/

相关文章:

java - Spring Boot无法运行data.sql来初始化数据库

java - Spring-boot中使用缓存抽象的缓存故障转移机制

java - 如何根据 URL 中的_escaped_fragment_ 重定向到 Tomcat?

java - 无法使用 PayPal Android SDK 进行付款

java - 在feign客户端拦截器中获取请求url

Java Spring Boot应用程序获得不同的系统时间

java - 如何删除 android v7 -app compat 支持

java - 双重加密/解密失败但单一加密/解密失败 - AES 256 位

应用程序上下文中的 Java bean 定义(Spring)

java - Spring Boot 中的日志文件端点