java - 在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 方法吗?
解决方案
容器注入的主要优点之一是您可以获得单例语义的好处,而不会出现“硬”单例的所有严重问题(例如难度测试)。摆脱getInstance
手动业务,让 Spring 负责确保为上下文创建和使用单个实例。
推荐阅读
- google-cloud-platform - 分析语法返回不准确的上下文结果
- php - 如何在不显示的情况下加载 php 文件?(/page.php -> /page)
- go - 附件名称中的 Unicode 字符
- python - 我正在尝试解决 0/1 背包问题,但我得到的输出与零一样多
- html - 非破坏空间(160)和正常空间(32)的宽度不同
- sql - 尝试连接 MySQL 服务器时出现“TDS 流中的协议错误”
- php - 正则表达式匹配任何字符,没有尾随/前导空格+最小/最大长度
- android - 我在 react Native 中有一个平面列表,但我按下按钮保存而不是自动重新加载数据
- mysql - Laravel Eloquent 急切地将多个关系加载到同一个模型会生成多个查询
- botframework - MSFT Teams 不使用 DATE 函数呈现自适应卡