I am using guava cache where I want to keep maximum size configurable. I tried using @value for this but the problem is private member cache gets created before @value injection. How can I read this size from config properties? The code I am currently using is given below
@Component
public class DataProcessor {
@Value("${cacheSize}")
private long cacheSize;
@Value(value = "${rawSensorDataTopic}")
private String rawSensorDataTopic;
private LoadingCache<String, DataPacketGroup> rfPacketsCache = CacheBuilder.newBuilder().maximumSize(cacheSize)
.concurrencyLevel(1).expireAfterWrite(15, TimeUnit.MINUTES)
.build(new CacheLoader<String, DataPacketGroup>() {
@Override
public DataPacketGroup load(String key) throws Exception {
return null;
}
});
You can put the cache creation in a method that is annotated with @PostConstruct
@Component
public class DataProcessor {
@Value("${cacheSize}")
private long cacheSize;
@Value(value = "${rawSensorDataTopic}")
private String rawSensorDataTopic;
private LoadingCache<String, DataPacketGroup> rfPacketsCache;
@PostConstruct
private void createcache() {
CacheBuilder.newBuilder().maximumSize(1000)
.concurrencyLevel(1).expireAfterWrite(15, TimeUnit.MINUTES)
.build(new CacheLoader<String, DataPacketGroup>() {
@Override
public DataPacketGroup load(String key) throws Exception {
return null;
}
});
}
This method will be executed if the bean is constructed and the properties are injected