java - 非 Spring 托管类上的 @Cacheable

标签 java spring spring-boot ehcache

我需要在非 Spring 托管类上使用 ehcache,例如实用程序类。它不起作用。我尝试初始化实用程序类对象,但仍然没有成功。我要创建对象的原因是,这个特定的类不能是单例对象,因为这个类有一些其他类变量,这些变量的值与同一类的其他对象不同。所以我不能用 @Component

注释这个类

实用类

public class DirectoryReader implements IReader {

    // Some other class variables, which values are different from other object of same class Ex. Delete the file after read.
    private boolean deleteFilesAfterRead;
    @Cacheable(cacheNames="directoryContent", unless="#result.length() > 0")
    public String getContent() {
        //Read a file and get data;
        return "";
    }
}

对象创建

@Component
public class ReaderUtility {
    @Autowired
    ApplicationContext applicationContext;
    @Bean(name="readers")
    public List<IReader> determineReader() {
        DirectoryReader directoryReader1 = new DirectoryReader();
        DirectoryReader directoryReader2 = new DirectoryReader();
        applicationContext.getAutowireCapableBeanFactory().initializeBean(directoryReader1, "directoryReader1");
        applicationContext.getAutowireCapableBeanFactory().initializeBean(directoryReader2, "directoryReader2");
        // List<IReader> readers = .....
        // return readers;
    }
}

最佳答案

如果制作单例是问题所在,为什么不使用 @Scope("prototype")这样每个请求都会创建一个新的bean?对于像您的情况一样有状态的 bean,您应该这样做。

https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-prototype

4.4.2 The prototype scope

The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made (that is, it is injected into another bean or it is requested via a programmatic getBean() method call on the container). As a rule of thumb, you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.

然后您可以将实用程序类更新为:

@Component
@Scope("prototype")
public class DirectoryReader implements IReader {

    // Some other class variables, which values are different from other object of same class Ex. Delete the file after read.
    private boolean deleteFilesAfterRead;
    @Cacheable(cacheNames="directoryContent", unless="#result.length() > 0")
    public String getContent() {
        //Read a file and get data;
        return "";
    }
}

关于java - 非 Spring 托管类上的 @Cacheable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50317905/

相关文章:

java - 在Android Studio上通过Intent将变量 "date"传递给另一个类,NULL OBJECT REFERENCE

java - Spring + Hibernate session 生命周期

spring - Swagger 2 (Spring Fox) 将 'es' 添加到我的 API 中

java - 如果你想访问encodeHexString等,你在哪里添加 'commons-codec-1.4.jar'?

java - 跳出循环

java - 在 REST 方法中获取原始请求( springframework )

java - Datatables Spring 4 Hibernate Tiles 3配置错误

java - Intellij 测试通过,mvn 测试失败

spring - 如果未经身份验证请求uri,如何让spring安全响应未经授权(http 401代码)

java - 如何检查 JAR 文件和 JAR 中特定文件的存在?