java - 我应该使用自动装配的静态变量吗?
问题描述
我正在尝试使用缓存功能实现单例模式。起初MySingleton
只是一个 POJO,事情很简单,但后来我需要添加一个新功能,这也需要自动装配一个 bean。(MyComponent
实际上是数据存储库的接口)
我把@Component
注释放在MySingleton
触发自动装配(即使它总是被称为静态方式)并创建了一个私有构造函数来将MyComponent
引用传递给由 new 创建的对象。这段代码似乎工作,虽然我不完全明白为什么。
我的问题:我觉得我做错了,但我是吗? (你会批准这个拉取请求到你的代码库吗?)
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class MySingletonTest {
@Test
public void test() {
assertNotNull(MySingleton.getInstance().getMyComponent());
}
}
// ----------------------------------------------------------------------------- //
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MySingleton {
private static final long CACHE_TIMEOUT = 60 * 60 * 1000; // 1 hour
private static final AtomicReference<MySingleton> INSTANCE = new AtomicReference<MySingleton>();
private final Calendar timestamp; // NOTE: this is NOT static!
@Autowired
private static MyComponent myComponent;
private MySingleton(MyComponent myComponent) {
this.timestamp = Calendar.getInstance();
MySingleton.myComponent = myComponent; // I do not understand why this line is needed
}
private boolean isTimeout() {
return Calendar.getInstance().getTimeInMillis() - timestamp.getTimeInMillis() > CACHE_TIMEOUT;
}
public static synchronized MySingleton getInstance() {
if ( INSTANCE.get() == null || INSTANCE.get().isTimeout() ) {
INSTANCE.set(new MySingleton(myComponent));
}
return INSTANCE.get();
}
public MyComponent getMyComponent() {
return myComponent;
}
}
// ----------------------------------------------------------------------------- //
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
}
解决方案
推荐阅读
- c++ - 如何使用 while 循环找到 GCD?模运算符如何工作?
- r - 有没有办法自动将文件名设置为列名?
- python - 使用未知编码解码字符串形式的字节
- ios - 无法安装“cordova-plugin-firebase-authentication”:未定义
- flutter - 电子邮件启动器中的 NULL 值
- android - onNotificationOpened 适用于 Android 模拟器,但不适用于实际设备
- php - 如何获取具有两列的连续数组?
- css - 可变网格间隙使网格父级的填充侵入网格元素
- flutter - 使用 Cypress 测试 Flutter 应用程序
- c++ - 为什么表达式的评估可能会产生副作用?