Java 找不到接口类型的Bean
首先,我想说的是,我已经阅读了类似的问题并实现了它们的答案,但似乎没有任何效果。 TL;博士,我正在实施一本书《春天》中的一个例子,这是我的问题。 初级班:Java 找不到接口类型的Bean,java,spring,spring-boot,model-view-controller,Java,Spring,Spring Boot,Model View Controller,首先,我想说的是,我已经阅读了类似的问题并实现了它们的答案,但似乎没有任何效果。 TL;博士,我正在实施一本书《春天》中的一个例子,这是我的问题。 初级班: package com.example.demo; @SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.demo.dao", "com.example.demo.model", "com.example.demo.service"}) pub
package com.example.demo;
@SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.demo.dao", "com.example.demo.model", "com.example.demo.service"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
控制器类:
package com.example.demo.api;
@Controller
@RequestMapping("/spittles")
public class SpittleController {
private SpittleRepository a;
@Autowired
public SpittleController(@Qualifier("abc") SpittleRepository a){
this.a = a;
}
}
接口:
package com.example.demo.dao;
@Repository("abc")
public interface SpittleRepository {
List<Spittle> findSpittles(long max, int count);
}
正如我之前所说,这个例子是从书中照搬过来的(为了回答这个问题,我简化了它)。此程序不会抛出错误的唯一情况是,我将注释:@ComponentScan(“com.example.demo.dao”)
添加到DemoApplication类中(但仅当dao中有一个文件时才有效)。或者,当我用class关键字替换interface关键字时,它也可以工作
有没有办法让类(DemoApplication)找到这个接口?注释
@Repository
应该用于类,而不是接口。看看这个
SpitleRepository
,并使用@Component
创建新类。这里需要接口的实现1.将对
com.example.demo
下的所有包进行组件扫描,因此不需要明确提及基本包。2.创建一个类并实现接口SpitleRepository
,并用@Component
注释新类。运行代码并告知结果2。我同意,我已经尝试过这个解决方案,它是有效的,但它是不可能的autowire只接口?(书中的家伙刚刚做了这件事)请确认在教程中存储库是否扩展了如下内容公共界面SpittleRepository扩展了JpaRepository{}
我将出版这本书:“首先,我们将定义一个数据访问存储库。为了分离数据而不是深入研究数据库的细节,我们将以接口的形式定义一个存储库,稍后我们将讨论实现(在第10章)。现在我们只需要一个接口来下载Spitle列表“这是书中的代码:公共接口SpittleRepository{list findSpittles(long max,int count);}
第10章中的实现是如何完成的?该接口需要一些实现才能正常工作,不是吗?遗憾的是,它也抛出了同样的错误:“需要一个类型为'com.example.demo.dao.SpitleRepository'的bean,但找不到它。”
Description:
Parameter 0 of constructor in com.example.demo.api.SpittleController required a bean of type 'com.example.demo.dao.SpittleRepository' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Qualifier(value="abc")
package com.example.demo.dao;
@Repository
public interface SpittleRepository {
List<Spittle> findSpittles(long max, int count);
}
package com.example.demo.api;
@Controller
@RequestMapping("/spittles")
public class SpittleController {
private SpittleRepository a;
@Autowired
public SpittleController(@Qualifier("spittleRepository ") SpittleRepository a){
this.a = a;
}
}