我正在构造函数中初始化需要 Autowiring 参数的加载缓存。但由于 spring bean 的顺序,我无法得到正确的结果。所以创建userLdapGroupsCache时没有设置超时和大小。你们有什么建议来解决这个问题吗?谢谢。
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);
}
});
}
最佳答案
您必须将该对象的初始化放在用@PostConstruct
注释的方法中:
@PostConstruct
public void init()
{
userLdapGroupsCache =
CacheBuilder.newBuilder()
.maximumSize(cacheMaxSize)
.expireAfterWrite(cacheExpireTime, TimeUnit.MINUTES)
...
}
感谢它会使用注入(inject)的参数进行初始化,因为在所有字段都注入(inject)到 bean 中之后调用使用 @PostConstruct
注释的方法。
关于java - 如何使构造函数在 Autowiring 后调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57332121/