首页 > 解决方案 > 我应该使用自动装配的静态变量吗?

问题描述

我正在尝试使用缓存功能实现单例模式。起初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 {

}

标签: javaspringspring-boot

解决方案


推荐阅读