Home > Software design >  Spring Boot MongoDB, insert data without a RestApi
Spring Boot MongoDB, insert data without a RestApi

Time:11-14

I have a Spring application working properly with MongoDB. I've set a RestApi structure and it works just fine when it comes to insert data, when the right endpoint is accessed.

But what I need to do is an application that doesn't work with RestApi system. I need to set a schedule and allow the software to save data regularly.

Just for testing reasons (and somehow close to the solution I need) I tried to access controller directly in main method of app, via Manager class:

public class Manager {

@Autowired
private StockController stockController;

public Manager(){

}

public boolean test(){
    LocalDateTime date = LocalDateTime.now();
    Stock stock = new Stock((double)500, "Test",date);

    stockController.saveStock(stock);
    System.out.println("stock saved");
    return true;
}

Main class:

@SpringBootApplication
public class ApiReaderApplication {

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

    Manager manager = new Manager();
    manager.test();


    }

}

However I keep getting NullPointerException, Java detects Manager's stockController instance as null when I use this syntax. Is there a way to achieve this? Controller class:

@AllArgsConstructor
@Controller
public class StockController {

    @Autowired
    private final StockService stockService;

    @PostMapping()
    public ResponseEntity<Stock> saveStock(Stock stock){
        return ResponseEntity.ok(stockService.saveStock(stock));
    }

}

Any orientation appreciated.

CodePudding user response:

need to set a schedule and allow the software to save data regularly

What you are looking for is probably a service with a @Scheduled method.

Example:

@Service
@RequiredArgsConstructor
public class Manager {

    private final StockService stockService;

    @Scheduled(fixedRate = 5000)
    public boolean test() {
        LocalDateTime date = LocalDateTime.now();
        Stock stock = new Stock((double)500, "Test",date);

        stockService.saveStock(stock);
        System.out.println("stock saved");
        return true;
    }
}

Also, you may want to enable the scheduler by adding @EnableScheduling on the main application class:

@SpringBootApplication
@EnableScheduling
public class ApiReaderApplication {

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

}

CodePudding user response:

  1. You should annotate Manager with @Service or @Component, and let spring boot initialize it.

You initializing it manually, so it's out of Spring context.

  1. It's better to autowire StockService in Manager and not StockController. Controllers are supposed to be used as Http API.
  • Related