【问题标题】:org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name userController : Unsatisfied dependencyorg.springframework.beans.factory.UnsatisfiedDependencyException:创建名为 userController 的 bean 时出错:不满足的依赖项
【发布时间】:2016-12-09 16:32:03
【问题描述】:

我尝试将 mysql 数据库连接到 Spring Boot Web 服务,但出现此错误,我不知道如何修复它...

我的控制器是:

    @RestController
    @RequestMapping("/user")
    public class UsersController {

    @Autowired
    UserService userService;

    @RequestMapping("/test")
    @ResponseBody
    String home(){
        return "Hello world";
    }

    @RequestMapping("/users")
    String test(){
        return "TEST ";
    }
}

我的实体是:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String username;
    private String name;
    private String firstname;
    private String email;
    private String adress;
    private String password;

    // Constructeur pour l'utilisation des JPA
    protected User(){}

    public User(String username, String name, String firstname, String email, String adress, String password) {
        this.username = username;
        this.name = name;
        this.firstname = firstname;
        this.email = email;
        this.adress = adress;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAdress() {
        return adress;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

我的存储库文件:

public interface UserRepository extends CrudRepository<User, Integer>{
    List<User> findUserByName(String name);
    User findUserByUsername(String username);
}

我的服务:

@Service
@Component
public class UserService {
    @Autowired
    private UserRepository repoUser;

    public List<User> getUser(String name){
        return repoUser.findUserByName(name);
    }
}

编辑: 这是我的堆栈跟踪:

2016-08-05 20:48:39.025  WARN 1849 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'usersController': Unsatisfied dependency expressed through field 'userService': No qualifying bean of type [services.UserService] found for dependency [services.UserService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [services.UserService] found for dependency [services.UserService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2016-08-05 20:48:39.026  INFO 1849 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2016-08-05 20:48:39.031  INFO 1849 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2016-08-05 20:48:39.053  INFO 1849 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report enable debug logging (start with --debug)


2016-08-05 20:48:39.073 ERROR 1849 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'usersController': Unsatisfied dependency expressed through field 'userService': No qualifying bean of type [services.UserService] found for dependency [services.UserService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [services.UserService] found for dependency [services.UserService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:313) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174) [spring-boot-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at com.example.JitBackofficeApplication.main(JitBackofficeApplication.java:13) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_101]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_101]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_101]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_101]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [services.UserService] found for dependency [services.UserService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1406) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1057) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    ... 24 common frames omitted

我的应用程序属性:

spring.datasource.url=jdbc:mysql://localhost/jitdatabase
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.data.jpa.repositories.enabled=true

这是我的申请文件:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("controllers")
public class JitBackofficeApplication {

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

here theres is my architecture

有人有解决办法吗?

问候

【问题讨论】:

  • 你的错误在哪里?
  • 错误出现在用户控制器上,因为我无法自动连接用户服务:/
  • 你的课程在哪些包中?
  • 不是这个问题的范围,但是,为什么要同时使用@Service@Component注解?
  • UserService 取决于 UserRepository。你确定它被正确实例化了吗?通常,您必须转到堆栈跟踪中的最后一个异常以获取实际错误/最上面的异常是原始问题的涟漪。

标签: java mysql spring spring-mvc spring-boot


【解决方案1】:

之前遇到过这个问题,追查发现不是controller和service的错误,而是repository的错误。我是通过异常栈'caused by xxx'得到的。终于找到原因了,我做了一个在application.properties中配置数据源时出错,导致无法连接数据库。

但是你的错误是不完整的。我认为你的错误和我的一样,我有一些问题需要确认。

1.你能展示你完整的异常堆栈吗?

2.你能展示你的application.properties吗?

3.你确定你的数据库可以连接成功吗?可以用jdbc测试一下。

4.您有一个或多个数据源吗?多了一个数据源会使配置变得复杂并且出错的可能性更大。

【讨论】:

  • 我编辑了我的问题,我的数据库正常工作,但我仍然不明白为什么我的网络服务无法正常工作......我认为问题与我的实体或存储库有关
  • 看到你的异常堆栈,我猜是因为@ComponentScan没有扫描你的服务。你能显示你的JitBackofficeApplication类吗。或者你确定你的ComponentScan配置正确吗?下面是我的: @ComponentScan("boot.web,boot.service,boot.repository,boot.app") 我的目录结构如下: src/main/ -----boot.app ---------- -App.java -----boot.domain -----boot.repository -----boot.service -----boot.web App.java 是我的启动类。
  • 我刚刚编辑了我的帖子(再次......)我有一张照片可以看到我的架构,但我不太了解 componentScan ...
  • @ComponentScan("controllers") 不包含service和repository,所以必须修改为@ComponentScan("controllers,services,repository,model") ComponentScan用于扫描bean类在加载spring容器时,如果没有配置组件的路径和服务库,依赖的类(如控制器)会加载失败。
【解决方案2】:

您的@ComponentScan 注释错误。您只需将控制器包添加为组件源。

您需要添加包含控制器和服务的包。

例如,如果你的包结构是:

com.mycompany.controllers

com.mycompany.services

然后将 com.mycompany 写入@ComponentScan

此外,您应该只在服务类上使用@Service,而不是@Component

【讨论】:

  • White 我的组件扫描应该怎么做?
  • 非常感谢您的帮助!
【解决方案3】:

我得到了相同的 UnsatisfiedDependencyException 和 NoSuchBeanDefinitionException,所以我检查了我的 @Service 注释在我的服务类之上,我的 @Repository 在我的 JPA 存储库类之上,我的主类有 @ComponentScan(basePackages = { "com.first.package.*", "com.second.package.*" })扫描我的存储库所在的包。

然后我注意到 2 个存储库具有相同的类名!一个在第一包,另一个在第二包!所以 Spring 只加载了一个,而不是第二个。 我重命名了第二个存储库,它起作用了!这也可以使用限定符来完成。

【讨论】:

    猜你喜欢
    • 2018-01-10
    • 2018-10-20
    • 2019-08-07
    • 2023-03-12
    • 1970-01-01
    • 2018-05-04
    • 2019-01-22
    • 2021-11-17
    • 2021-08-25
    相关资源
    最近更新 更多