【问题标题】:APPLICATION FAILED TO START when I try to work with mongoDB and SpringBoot当我尝试使用 mongoDB 和 Spring Boot 时应用程序无法启动
【发布时间】:2021-04-07 04:05:17
【问题描述】:

我已经实现了一个 spring boot 应用程序来从文件中检索文件数据并将其保存在单独的集合中。当我运行应用程序时,它会出现以下错误。我无法解决它。谁能帮我做这件事?

错误

Description:
    
    Parameter 2 of constructor in com.bezkoder.spring.jwt.mongodb.SpringBootSecurityJwtMongodbApplication required a bean of type 'com.bezkoder.spring.jwt.mongodb.models.LogRecordCollection' that could not be found.
    
    
    Action:
    
    Consider defining a bean of type 'com.bezkoder.spring.jwt.mongodb.models.LogRecordCollection' in your configuration.
    
    Disconnected from the target VM, address: '127.0.0.1:55297', transport: 'socket'

LogRecordController.java

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth/log")
public class LogRecordController {

    @Autowired
    LogRecordRepository logRecordRepository;

    @GetMapping("")
    public ResponseEntity<?> getAllLogRecordsByLogFileId(@RequestParam("fileId") String fileId) {
        try{
            LogRecordCollection logRecordCollection = new LogRecordCollection();
            logRecordCollection.setCollectionName(fileId);
            // List<LogRecord> logRecords = logRecordRepository.findAll(PageRequest.of(1, 10, Sort.by(Sort.Direction.ASC, "no"))).getContent();
            List<LogRecord> logRecords = logRecordRepository.findAll();
            return ResponseEntity.ok().body(logRecords);
        }catch (Exception e){
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(e.getMessage());
        }
    }

}

SpringBootSecurityJwtMongodbApplication.java

@SpringBootApplication
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth/logFile")
public class SpringBootSecurityJwtMongodbApplication {

    public SpringBootSecurityJwtMongodbApplication(LogFileRepository logfileRepo, LogRecordRepository logrecordRepo, LogRecordCollection logrecordColl) {
        this.logfileRepo = logfileRepo;
        this.logrecordRepo = logrecordRepo;
        this.logrecordColl = logrecordColl;
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringBootSecurityJwtMongodbApplication.class, args);
    }




    @Bean
    public ApplicationRunner runner(FTPConfiguration.GateFile gateFile) {
        return args -> {
            List<File> files = gateFile.mget(".");
            for (File file : files) {
                JSONArray arr = new JSONArray();
                System.out.println("Result:" + file.getAbsolutePath());
                run(file, arr);
            }
        };
    }

    void run(File file, JSONArray arr) throws IOException {
        SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
        Pcap pcap = Pcap.openStream(file);
        JSONObject obj = new JSONObject();
        String fileName = file.getName();
        pcap.loop(
                packet -> {
                    String Time = null;
                    String Source = null;
                    String Destination = null;
                    String dataProtocol = null;
                    Long Length = null;

                    if (packet.hasProtocol(Protocol.TCP)) {
                        TCPPacket packet1 = (TCPPacket) packet.getPacket(Protocol.TCP);
                        Time = formatter.format(new Date(packet1.getArrivalTime() / 1000));
                        Source = packet1.getSourceIP();
                        Destination = packet1.getDestinationIP();
                        dataProtocol = packet1.getProtocol().toString();
                        Length = packet1.getTotalLength();

                    } else if (packet.hasProtocol(Protocol.UDP)) {
                        UDPPacket packet1 = (UDPPacket) packet.getPacket(Protocol.UDP);
                        Time = formatter.format(new Date(packet1.getArrivalTime() / 1000));
                        Source = packet1.getSourceIP();
                        Destination = packet1.getDestinationIP();
                        dataProtocol = packet1.getProtocol().toString();
                        Length = packet1.getTotalLength();

                    } else {
                        System.out.println("Not found protocol. | " + packet.getProtocol());
                    }

                    obj.put("Time", Time);
                    obj.put("Source", Source);
                    obj.put("Destination", Destination);
                    obj.put("Protocol", dataProtocol);
                    obj.put("Length", Length);
                    arr.add(obj);
                    return packet.getNextPacket() != null;
                }
        );
        System.out.println(arr);
        System.out.println(fileName);
        Calendar calendar = Calendar.getInstance();
        String now = String.valueOf(calendar.getTime());
        LogFile data =logfileRepo.save(new LogFile("", fileName, now));

        String collectionName = data.getFileName();
        System.out.println(collectionName);
        //Converting jsonData string into JSON object

        //Creating an empty ArrayList of type Object
        ArrayList<Object> listdata = new ArrayList<>();
        //Checking whether the JSON array has some value or not
        if (arr != null) {

            //Iterating JSON array
            for (int i=0;i<arr.size();i++){

                //Adding each element of JSON array into ArrayList
                listdata.add(arr.get(i));
            }
        }
        logrecordColl.setCollectionName(collectionName);
        listdata.addAll(logrecordRepo.findAll());
        
    }
    private final LogFileRepository logfileRepo;
    private final LogRecordRepository logrecordRepo;
    private final LogRecordCollection logrecordColl;
}

LogRecordRepository.java

import com.bezkoder.spring.jwt.mongodb.models.LogRecord;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface LogRecordRepository extends MongoRepository<LogRecord, String>{


}

LogRecordCollection.java

public class LogRecordCollection {
    private static String collectionName = "undefined";

    public static String getCollectionName(){
        return collectionName;
    }

    public void setCollectionName(String collectionName){
        this.collectionName = collectionName;
    }

}

【问题讨论】:

    标签: java arrays mongodb spring-boot spring-data


    【解决方案1】:

    com.bezkoder.spring.jwt.mongodb.SpringBootSecurityJwtMongodbApplication 中构造函数的参数 2 需要一个无法找到的 'com.bezkoder.spring.jwt.mongodb.models.LogRecordCollection' 类型的 bean。

    简而言之,这样的异常是不言自明的。这意味着 Spring 找不到要注入到您的类中的 bean

    在您的情况下,SpringBootSecurityJwtMongodbApplication 类有一个构造函数:

    public SpringBootSecurityJwtMongodbApplication(LogFileRepository logfileRepo, LogRecordRepository logrecordRepo, LogRecordCollection logrecordColl) {
            this.logfileRepo = logfileRepo;
            this.logrecordRepo = logrecordRepo;
            this.logrecordColl = logrecordColl;
        }
    

    现在,LogRecordCollection 必须是一个 bean(例如,用 @Component 注释,或者通过 java 配置定义(@Configuration 标记的类和用 @Bean 注释的方法创建这个类)。否则 spring 赢了't "识别" 这个类是一个 bean。

    所以严格来说这是你的问题。

    现在,话虽如此-您在问题中提供的代码看起来非常混乱-您将@SpringBootApplication(它是应用程序的入口点)与其他控制器混合在一起。我真的建议您将所有这些文件分开到不同的文件中,以提高代码清晰度并避免可能难以修复的意外异常。

    【讨论】:

    • 非常感谢您的回答。现在它起作用了。我是弹簧靴的新手,是的,我搞砸了这些是正确的。我会纠正他们。
    【解决方案2】:

    在 SpringBootSecurityJwtMongodbApplication 中添加以下注解

    @SpringBootApplication
    @ComponentScan("com.bezkoder.spring.jwt.mongodb") //to scan packages mentioned
    @EnableMongoRepositories("com.bezkoder.spring.jwt.mongodb") //to activate MongoDB repositories
    public class SpringBootSecurityJwtMongodbApplication { ... }
    

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 2015-05-10
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-26
      相关资源
      最近更新 更多