gpt4 book ai didi

java - 非 Spring 托管类上的 @Cacheable

转载 作者:行者123 更新时间:2023-12-02 11:15:21 24 4
gpt4 key购买 nike

我需要在非 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com