繁体   English   中英

Spring Boot 无法扫描 MongoRepository

[英]Spring Boot unable to scan MongoRepository

我有一个实现MongoRepository接口的持久性接口,如下所示:

package org.prithvidiamond1.DB.Repositories;

import org.prithvidiamond1.DB.Models.SomeModel;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ServerRepository extends MongoRepository<SomeModel, String> {
}

尽管如此,我仍然收到以下错误:

Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'botApplication': 
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'org.prithvidiamond1.DB.Repositories.ServerRepository' available: expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {}


PPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in org.prithvidiamond1.BotApplication required a bean of type 'org.prithvidiamond1.DB.Repositories.ServerRepository' that could not be found.


Action:

Consider defining a bean of type 'org.prithvidiamond1.DB.Repositories.ServerRepository' in your configuration.

我尝试了很多解决方案(自定义@ComponentScan ,使用@Service而不是@Component等)我在互联网上找到但没有一个可以帮助我解决问题,有人可以向我解释什么是错误的以及我应该如何解决这个问题?

注意:目录结构如下(这不是完整的目录结构,但我想这应该足够了解了):

org.prithvidiamond1
   |
   +--BotApplication.java
   |
   +--DB
      |
      +--Repository
      |
      +--ServerRepository.java

BotApplication.java如下所示:

package org.prithvidiamond1;

import org.jc.api.Api;
import org.jc.api.ApiBuilder;
import org.jc.api.entity.server.Server;
import org.prithvidiamond1.DB.Models.Server;
import org.prithvidiamond1.DB.Repositories.ServerRepository;
import org.slf4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class BotApplication {
    private final Api api;
    private final ServerRepository serverRepository;

    public BotApplication(ServerRepository serverRepository, Logger logger){
        String botToken = System.getenv().get("BOT_TOKEN");

        this.api = new ApiBuilder();

        this.serverRepository = serverRepository;

        appRuntime(logger);
    }

    public void appRuntime(Logger logger){
        logger.info("Bot has started!");

        // Handling server entries in the database
        if (this.serverRepository.findAll().isEmpty()) {
            logger.trace("server data repository empty, initializing data repository...");
            Collection<Server> servers = api.getServers();
            for (Server server : servers) {
                this.serverRepository.save(new Server(String.valueOf(server.getId())));
            }
            logger.trace("server data repository initialized");
        }
    }

    @Bean
    public Api getApi() {
        return this.api;
    }
}

编辑:这是一个包含所有代码的存储库的链接: https ://github.com/prithvidiamond1/DiamondBot/tree/springboot-restructure

使用注释@Autowired和 BotApplication 类的构造函数,如下所示 -

@Autowired
public BotApplication(ServerRepository serverRepository, Logger logger){
        String botToken = System.getenv().get("BOT_TOKEN");

        this.api = new ApiBuilder();

        this.serverRepository = serverRepository;

        appRuntime(logger);
    }

您需要在主应用程序类之上使用 @EnableMongoRepositories 来启用对 mongo 存储库 bean 的扫描。

您已经在应用程序中创建了Repository bean (ServerRepository)。

但是在您的BotApplication组件(它本身是一个 bean)中,您并没有告诉 spring 注入Repository bean 的依赖项(即 Dependancy Injection)。

这种依赖注入可以通过构造函数、基于字段或基于设置器的方法来实现。

您可以从public BotApplication(ServerRepository serverRepository, Logger logger)构造函数中删除ServerRepository serverRepository & 只需使用:

@Autowired
private final ServerRepository serverRepository;

或者作为其他答案建议,在构造函数本身中使用 @Autowired 并删除字段ServerRepository serverRepository

`
@Autowired
public BotApplication(ServerRepository serverRepository, Logger logger)
`

请注意,这里this.serverRepository = serverRepository; 在构造函数中也不需要,因为依赖注入会解决这个问题。

问题是您正在使用主要源类( BotApplication.class )在启动期间执行自定义代码。

    public static void main(String[] args) {
        ApplicationContext AppContext = SpringApplication.run(BotApplication.class, args);
    }

    public BotApplication(DiscordServerRepository serverRepository, Logger logger){
        ...
        appRuntime(logger);
    }

SpringApplication.run方法中,您只需要传递提供 bean 定义的类。 这些是@Configuration类。 这不是使用存储库或任何启动代码的好地方。
查看最佳实践Spring Boot 启动后运行代码

我描述了最好的解决方案之一: ApplicationRunner

  1. BotApplication类必须实现ApplicationRunner接口。 该接口用于指示 bean 在包含在SpringApplication中时应该运行。
    run方法中执行所有启动代码。
@Component
public class BotApplication implements ApplicationRunner {
    private final DiscordApi api;
    private final DiscordServerRepository serverRepository;

    private final Logger logger;

    public BotApplication(DiscordServerRepository serverRepository, Logger logger){
        String botToken = System.getenv().get("BOT_TOKEN");
        this.logger = logger;
        this.serverRepository = serverRepository;
        this.api = new DiscordApiBuilder()
                .setToken(botToken)
                .setAllIntents()
                .setWaitForServersOnStartup(true)
                .setWaitForUsersOnStartup(true)
                .login().exceptionally(exception -> {    // Error message for any failed actions from the above
                    logger.error("Error setting up DiscordApi instance!");
                    logger.error(exception.getMessage());
                    return null;
                })
                .join();
    }

    public void appRuntime(Logger logger){
        logger.info("Bot has started!");

        // Handling server entries in the database
        if (this.serverRepository.findAll().isEmpty()) {
            logger.trace("Bot server data repository empty, initializing data repository...");
            Collection<Server> servers = api.getServers();
            for (Server server : servers) {
                this.serverRepository.save(new DiscordServer(String.valueOf(server.getId()), Main.defaultGuildPrefix));
            }
            logger.trace("Bot server data repository initialized");
        }
    }

    @Bean
    public DiscordApi getApi() {
        return this.api;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        appRuntime(logger);
    }
}
  1. Main.class传递给SpringApplication.run
@SpringBootApplication
@EnableMongoRepositories
public class Main {
    public static void main(String[] args) {
        ApplicationContext AppContext = SpringApplication.run(Main.class, args);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM