lundi 21 septembre 2020

Call singleton class in spring boot rest api controller

I am new to spring framework. I have to use spring boot and have a rest controller as below :-

@RestController
public class StatisticsController {

    private TransactionCache transactionCache;

    public StatisticsController(TransactionCache transactionCache) {
        this.transactionCache = transactionCache;
    }

    @PostMapping("/tick")
    public ResponseEntity<Object> addInstrumentTransaction(@Valid @RequestBody InstrumentTransaction instrumentTransaction) {
        transactionCache.addTransaction(instrumentTransaction);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

and I have a class which needs to be singleton :-

@Component
public class TransactionStatisticsCacheImpl implements TransactionCache {

    private static TransactionStatisticsCacheImpl instance;

    public static TransactionStatisticsCacheImpl getInstance(){

        if(Objects.isNull(instance)){
            synchronized (TransactionStatisticsCacheImpl.class) {
                if(Objects.isNull(instance)){
                    instance = new TransactionStatisticsCacheImpl();
                }
            }
        }

        return instance;
    }

    private TransactionStatisticsCacheImpl() {}

I want to know the correct way to call this singleton class in my rest controller. I know that by default the scope of a bean in spring is singleton. Is this the correct way to call the singleton class in rest controller?

@RestController
public class StatisticsController {

    private TransactionCache transactionCache;

    public StatisticsController(TransactionCache transactionCache) {
        this.transactionCache = transactionCache;
    }

    @PostMapping("/tick")
    public ResponseEntity<Object> addInstrumentTransaction(@Valid @RequestBody InstrumentTransaction instrumentTransaction) {
        transactionCache.addTransaction(instrumentTransaction);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

or

We need to call it using the getInstance() method? Also do we need to explicitly have the getInstance method in the TransactionStatisticsCacheImpl class?

Aucun commentaire:

Enregistrer un commentaire