使用spring-boot在依赖项注入中创建bean时出错

时间:2019-05-23 15:48:36

标签: java spring spring-boot dependency-injection

这是我的代码-https://github.com/iyngaran/to-do-list

我在info.iyngaran.core.auth.repository包中有UserRepository类,并用@Repository进行了注释。

当我尝试将其注入CustomUserDetailsService包中的info.iyngaran.core.auth.security类中时,出现以下错误。

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customUserDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'info.iyngaran.core.auth.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

有人可以帮我找出这个问题吗?预先感谢。

2 个答案:

答案 0 :(得分:1)

我通过在Spring Boot主类中添加以下行来解决此问题。

@EnableJpaRepositories({"info.iyngaran.core","info.iyngaran.todolistapi"})

这解决了我的问题。详细信息-https://stackoverflow.com/a/53172477/9348637

答案 1 :(得分:0)

主要问题是组件扫描。因此,请按照以下方式安排代码

将您的TodolistApiApplication类移动到包根info.iyngaran

清除混乱

package info.iyngaran;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import java.util.TimeZone;

@SpringBootApplication
public class TodolistApiApplication {

    @PostConstruct
    void init() {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }


    public static void main(String[] args) {
        SpringApplication.run(TodolistApiApplication.class, args);
    }

}

还使用构造函数注入(此修复不是必需的)。现场注入是非常糟糕的做法

private final UserRepository userRepository;

public CustomUserDetailsService(UserRepository userRepository) {
    this.userRepository = userRepository;
}