我制作了一个测试Spring应用程序->服务->库
控制器->
@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 ProductServiceImpl中这样做;--他发誓说,这里没有豆子。-我在应用程序Bean -它开始发誓,它现在不能为ProductRepository (接口)找到一个Bean -当我从服务调用它。如何为接口制作bean?
发布于 2018-12-01 15:46:07
我认为您的问题在于@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注释@Entity对您的产品实体进行分析。
https://stackoverflow.com/questions/53572073
复制相似问题