首页 > 解决方案 > 在spring boot rest api控制器中调用单例类

问题描述

我是弹簧框架的新手。我必须使用弹簧靴并有一个休息控制器,如下所示:-

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

我有一个需要单身的班级:-

@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() {}

我想知道在我的休息控制器中调用这个单例类的正确方法。我知道默认情况下,spring 中 bean 的范围是单例的。这是在休息控制器中调用单例类的正确方法吗?

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

或者

我们需要使用 getInstance() 方法调用它吗?我们还需要在 TransactionStatisticsCacheImpl 类中显式地拥有 getInstance 方法吗?

标签: javaspringspring-bootrestdesign-patterns

解决方案


容器注入的主要优点之一是您可以获得单例语义的好处,而不会出现“硬”单例的所有严重问题(例如难度测试)。摆脱getInstance手动业务,让 Spring 负责确保为上下文创建和使用单个实例。


推荐阅读