[英]Getting error related with bean creation while run Spring Boot app
I am learning spring boot with JPA and i have a problem when launch my app.我正在使用 JPA 学习 spring 引导,并且在启动我的应用程序时遇到问题。 Could somebody help me to solve this issue?
有人可以帮我解决这个问题吗? Error is -
错误是 -
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.
Controller Controller
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存储库
@Repository
public interface UserRepo extends JpaRepository<User, Integer> {
}
Application class应用 class
@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);
}
}
Project structure项目结构
I annotated repository with @Repository and using @Autowired on controller.我使用@Repository 注释存储库并在controller 上使用@Autowired。 Where i am doing wrong?
我在哪里做错了?
You added quite a lot annotations
which aren't really needed.您添加了很多实际上并不需要的
annotations
。
Make the following changes进行以下更改
DemoController.java -> Add `@Controller or @RestController` annotation
Application.java --> Remove annotations completely
@ComponentScan()
@EnableJpaRepositories()
@EnableAutoConfiguration()
Let me know if it works.让我知道它是否有效。
Try.尝试。
You are probably missing the @EnableJpaRepositories
annotation in your configuration class.您可能在配置 class 中缺少
@EnableJpaRepositories
注释。 This will then scan for all classes with the @Repository
annotation.然后,这将扫描所有带有
@Repository
注释的类。
Can you share the package structure of your project?你能分享一下你项目的package结构吗?
I doubt that component scan is unable to scan your UserRepo class.我怀疑组件扫描无法扫描您的UserRepo class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.