Мне нужно использовать ehcache для управляемого класса, отличного от Spring, например служебного класса. Это не работает. Я попытался инициализировать объект служебного класса, но все равно не повезло. Причина, по которой я собираюсь создать объект, заключается в том, что этот конкретный класс не может быть одноэлементным объектом, потому что этот класс имеет некоторые другие переменные класса, значения которых отличаются от других объектов того же класса. Поэтому я не могу аннотировать этот класс с помощью @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;
}
}
@SeverityOne Я обновлю вопрос, я имел в виду другое значение поля.
Spring необходимо проксировать объекты, в которых вы хотите использовать их функциональность. Вы можете пересмотреть структуру своего кода, чтобы переместить @Cachable в управляемый компонент.
@SomasundaramSekar Понятно, но не уверен, поддерживает ли Spring несколько bean-компонентов для одного и того же класса. Если так, я могу это использовать. Любая идея?




Если проблема заключается в создании синглтона, почему бы не использовать @Scope("prototype"), чтобы новый bean-компонент создавался с каждым запросом? Это то, что вы должны делать для bean-компонентов с отслеживанием состояния, как в вашем случае.
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 "";
}
}