java - Spring DI for Repository (JAVA)
问题描述
我制作了一个测试 Spring Controller 应用程序 -> 服务 -> 存储库
控制器->
@RestController
public class HelloController {
@Autowired
private ProductServiceImpl productService;
@RequestMapping("/getAll")
public List getAll(){
return productService.getAll();
}
}
服务 ->
@Service
public class ProductServiceImpl implements Services.ProductService {
@Autowired
private ProductRepository productRepository;
@Override
public List<Product> getAll() {
return productRepository.findAll();
}
}
存储库->
@Repository
public interface ProductRepository extends JpaRepository<Product,Long> {
}
应用 ->
@SpringBootApplication
@EnableJpaRepositories("Repository")
@ComponentScan("com.lopamoko")
public class CloudliquidApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(CloudliquidApplication.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
我正在尝试在控制器中做 @Autowired private ProductServiceImpl productServiceImpl; - 他发誓这没有豆子。- 我在应用程序 Bean 中做 - 它开始发誓,它现在找不到 ProductRepository(接口)的 Bean - 当我从服务中调用它时。如何为接口制作 bean?
解决方案
我认为您的问题在于 value@EnableJpaRepositories
可能是误导性的,并且它指向了错误的包?的值@EnableJpaRepositories
表示要扫描存储库的基本包。
如果 ProductRepository 位于“com.lopamoko”中,您可以将该值留空。
@SpringBootApplication
@EnableJpaRepositories
@ComponentScan("com.lopamoko")
public class CloudliquidApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(CloudliquidApplication.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
因为您已经指定了要在其中扫描的包@ComponentScan("com.lopamoko")
如果您的存储库位于不同的包中,则需要将包指定为@EnableJpaRepositories
@SpringBootApplication
@EnableJpaRepositories("com.repository")
@ComponentScan("com.lopamoko")
public class CloudliquidApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(CloudliquidApplication.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
不要忘记使用 JPA 注释来注释您的 Product 实体@Entity
推荐阅读
- flutter - 执行命令时 Flutter android 许可证状态未知
- ios - PencilKit 将背景图像和绘图保存到相册 Xcode
- html - 如何在 div 中的 div 之后放置文本?
- python - 如何在 Tkinter GUI 中将相同的方法应用于包含不同小部件的两个不同框架
- python - 'float' 对象不能被解释为整数 - 从 python2.X 到 python3.8
- http-status-code-404 - rust/mdBook:如果地址是子文件夹,则显示不带 CSS 的 404 页面
- mongodb - 如何强制 mongo db $or 查询首先检查第一个提供的值,如果没有找到则只回退到第二个?
- laravel - 车辆与价格之间的雄辩关系
- node.js - AWS Lambda:同步调用流
- java - Kafka Connect:Rest API Source Connector 连接被拒绝