Issue
I am initializing a load cache in the constructor which needs autowired parameters. But due to spring bean sequence, I can' t get it right. So userLdapGroupsCache is created without setting timeout and size. Do you guys have any suggestion to fix this? Thanks.
private LoadingCache<String, Set<String>> userLdapGroupsCache;
@Autowired
@Qualifier("cacheExpireTime")
private int cacheExpireTime;
@Autowired
@Qualifier("cacheMaxSize")
private int cacheMaxSize;
public LdapAuthorization ()
{
userLdapGroupsCache =
CacheBuilder.newBuilder()
.maximumSize(cacheMaxSize)
.expireAfterWrite(cacheExpireTime, TimeUnit.MINUTES)
.build(new CacheLoader<String, Set<String>>() {
@Override
public Set<String> load(String key) throws Exception {
return getGroups(key);
}
});
}
Solution
You have to put the initialization of that object inside a method annotated with @PostConstruct
:
@PostConstruct
public void init()
{
userLdapGroupsCache =
CacheBuilder.newBuilder()
.maximumSize(cacheMaxSize)
.expireAfterWrite(cacheExpireTime, TimeUnit.MINUTES)
...
}
Thanks to that it will be initialized with injected parameters as methods annotated with @PostConstruct
are invoked after all of the fields have been injected into the bean.
Answered By - Maciej Kowalski