在运行Spring Boot应用程序时遇到与bean创建相关的错误

时间:2019-10-20 11:17:16

标签: java spring-boot jpa spring-data-jpa

我正在学习使用JPA进行春季启动,并且在启动我的应用程序时遇到问题。有人可以帮我解决这个问题吗?错误是-

Description: Field userRepo in com.example.demo.controller.DemoController required a bean of type 'com.example.demo.repo.UserRepo' that could not be found. The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true) 
Action: Consider defining a bean of type 'com.example.demo.repo.UserRepo' in your configuration.

控制器

public class DemoController {
private static final String CLASS_NAME = DemoController.class.getName();
@Autowired
private UserRepo userRepo;

@Autowired
private UserServiceImpl userService;

  @PostMapping(value = "/hello", consumes = "application/json", produces = "application/json") 
  public String createUser(@RequestBody User user) {
       long count = userRepo.count();
      return "Done"; 
  }
}

存储库

@Repository

public interface UserRepo extends JpaRepository<User, Integer> {    
}

应用程序类

@SpringBootApplication
@ComponentScan("com.example.demo*")
@EnableJpaRepositories(basePackages = {"com.example.demo*"})
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class DemoApplication {

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

}

项目结构

enter image description here

我用@Repository注释了存储库,并在控制器上使用@Autowired。我在哪里做错了?

3 个答案:

答案 0 :(得分:1)

您添加了很多annotations,但实际上并不需要。

进行以下更改

     DemoController.java -> Add `@Controller or @RestController` annotation
     Application.java --> Remove annotations completely

    @ComponentScan() 
    @EnableJpaRepositories()
    @EnableAutoConfiguration()

让我知道它是否有效。

尝试。

答案 1 :(得分:0)

您可能在配置类中缺少@EnableJpaRepositories注释。然后,它将扫描带有@Repository批注的所有类。

答案 2 :(得分:0)

您有很多不必要的注释。

根据文档-

我们通常建议您将主应用程序类放在其他类之上的根包中。

我怀疑组件扫描无法扫描您的 UserRepo 类。

删除所有不必要的注释。

@ComponentScan("com.example.demo*")
@EnableJpaRepositories(basePackages = {"com.example.demo*"})
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})