user11725933
user11725933

Reputation:

APPLICATION FAILED TO START when I try to work with mongoDB and SpringBoot

I have implemented a spring boot application to retrieve file data from files and save it in separate collections. When I run the application it gives the following error. I couldn't resolve it. Can anyone help me to do this?

Error

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;
    }

}

Upvotes: 0

Views: 123

Answers (2)

Mark Bramnik
Mark Bramnik

Reputation: 42481

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.

In an nutshell, the exception like this is self-explanatory. It means that Spring could not find a bean to be injected into your class

In your case the class SpringBootSecurityJwtMongodbApplication has a constructor:

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

Now, LogRecordCollection has to be a bean (annotated with @Component for example, or defined in via java configuration (@Configuration marked classes and method annotated with @Bean that creates this class). Otherwise spring won't "recognize" this class a bean.

So strictly speaking this is your issue.

Now, having said that - the code you've presented in the question looks extremely messy - you mix @SpringBootApplication which is an entry point to the application, the rest controller and what not. I really recommend you to separate all this to different files to improve the code clarity and avoid unexpected exceptions that can be tricky to fix.

Upvotes: 2

Kaumadie Kariyawasam
Kaumadie Kariyawasam

Reputation: 1456

add below annotations in 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 { ... }

Upvotes: 1

Related Questions