无法实例化Spring bean存储库 [英] Can't instantiate Spring bean repository

查看:135
本文介绍了无法实例化Spring bean存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此任务中,我不允许使用自动接线

In this task I am not allowed to use auto-wiring

所以我正在尝试创建类似以下内容: https://www.tutorialspoint. com/spring/spring_java_based_configuration.htm

so I am trying to create something similar to this: https://www.tutorialspoint.com/spring/spring_java_based_configuration.htm

我的代码

@Configuration
public class ApplicationConfig {

    @Bean
    public FoodService foodService() {
        return new FoodService(FoodRepository());
    }

    @Bean
    public FoodRepository foodRepository() {
        return new FoodRepository();
    }
}

当然,因为FoodRepository是扩展MongoRepository的接口,所以它给出一个错误,即尚未实例化,并且可以肯定,在服务内部,我需要调用Repository进行保存等.该如何解决?

Of course since FoodRepository is an interface extending MongoRepository, it gives an error that it has not been instantiated, and for sure inside the service I need to be calling the Repository to save and such. How to solve this?

推荐答案

我在在ApplicationConfig.java内部,我应该执行以下操作:

Inside ApplicationConfig.java I should have done the following:

@Configuration
@EnableMongoRepositories("com.food.repository")
public class ApplicationConfig {
@Value("${spring.data.mongodb.host}")
private String mongoHost;

@Value("${spring.data.mongodb.port}")
private int mongoPort;

@Value("${spring.data.mongodb.database}")
private String mongoDB;

@Bean
public foodService foodService() {
    MongoOperations operations = new MongoTemplate(new MongoClient(mongoHost,mongoPort), mongoDB);
    MongoRepositoryFactory factory = new MongoRepositoryFactory(operations);
    foodRepository foodRepository = factory.getRepository(foodRepository.class);
    return new foodService(foodRepository);
}

这篇关于无法实例化Spring bean存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆