首页 > 解决方案 > 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?

标签: javaspringspring-data-jpainversion-of-control

解决方案


我认为您的问题在于 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


推荐阅读