如何修复spring boot中的“ Application failed start”,并要求定义bean

问题描述 投票:0回答:2

我的Spring启动应用程序运行,但说无法启动,它说:

com.example.security.WebSecurityConfiguration中的字段userDetailsS​​ervice需要一个无法找到的类型为“com.example.security.UserDetailsS​​erviceImpl”的bean。

注入点具有以下注释:

  • @org.springframework.beans.factory.annotation.Autowired(required=true)

考虑在配置中定义类型为“com.example.security.UserDetailsS​​erviceImpl”的bean。

我尝试在我的UserDetailsS​​erviceImpl类中添加@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应用程序。

java spring spring-boot spring-security dependency-injection
2个回答
3
投票

在这种情况下,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...
    }
}

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


1
投票

将@Service注释放在UserDetailsS​​erviceImpl类上。

© www.soinside.com 2019 - 2024. All rights reserved.