你好,我在一个类里面声明了4个cache对象,如下
@Component
class CacheObj {
@CreateCache(name = CacheKey.VISIBLE_DATA_ACCESS,cacheType = CacheType.BOTH)
lateinit var visibleDataCache: Cache<String, Boolean>
@CreateCache(name = CacheKey.SUBSCRIPT, cacheType = CacheType.LOCAL)
lateinit var subscriptCache: Cache<String, SubscriptPage>
@CreateCache(name = CacheKey.ORBIT_TRACK, cacheType = CacheType.LOCAL, expire = 10, timeUnit = TimeUnit.MINUTES)
lateinit var orbitTrackCache: Cache<String, Orbital.OrbitalData>
@CreateCache(name = CacheKey.YC_PARAM,cacheType = CacheType.LOCAL)
lateinit var ycCache: Cache<String, YCParam?>
}
但是使用的时候却发现这4个cache都为null
通过debug源码 发现在 CreateCacheAnnotationBeanPostProcessor
类中
@Override
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
beanFactory.registerDependentBean(beanName, "globalCacheConfig");
LazyInitCache cache = new LazyInitCache(beanFactory, ann, field);
field.setAccessible(true);
field.set(bean, cache);
}
是有初始化该Bean的这4个对象并给他们赋值了 LazyInitCache
但是当使用的时候却发现这四个属性为空,并且 LazyInitCache
的 checkInit()
方法一直没有被调用,不知道出了什么问题,为什么这个bean的属性被置空,这是我调用的地方
@Aspect
@Component
class CacheAop {
@Autowired
lateinit var cacheObj: CacheObj
@Pointcut("@annotation(com.waytogalaxy.display.common.config.cacheConfig.CacheClear)")
fun findCacheClear() {
}
/**
* 清理对应的name属性的缓存
*/
@Before("findCacheClear()")
fun doClear(joinPoint: JoinPoint) {
val signature = joinPoint.signature
if (signature is MethodSignature) {
val method = signature.method
val cacheClear = method.getAnnotation(CacheClear::class.java)
val cacheName = cacheClear.name
val cache = findMatchNameCache( cacheName) ?: return
cache.clear(cacheName)
}
}
/**
* 获取缓存名字对应的缓存对象
* @param cacheName 缓存名称
*/
private fun findMatchNameCache(cacheName: String): Cache<*, *>? {
val fields = CacheObj::class.java.declaredFields
val field = fields?.firstOrNull {
val anno = it.getAnnotation(CreateCache::class.java)
anno.name == cacheName
}
if (field != null && field.type == Cache::class.java) {
return field.get(cacheObj) as Cache<*, *>
} else{
return null
}
}
}
3条答案
按热度按时间kiz8lqtg1#
我看你是通过反射方式获取字段的,是不是初始化顺序方面的原因?
pxy2qtax2#
这个方法是在spring启动后调用的,我看到CreateCache应该是在启动的过程中赋值的,应该不是顺序的问题。
m2xkgtsf3#
刚刚我试了给
CacheObj
加了个uuid
,var uuid = UUID.randomUUID()
发现在程序启动的时候,
jetCache
给cacheObj
赋值的时候,uuid
是有值的,但是当程序启动完毕,执行clear
方法,cacheObj
对象是没有值的,是不是在jetCache
初始化的cacheObj
和启动完毕之后的cacheObj
不是同一个对象是我的问题,不能通过反射获取代理对象对应的字段,通过debug发现代理对象的属性就是为空,但是代理的目标对象是有属性的