使用 Spring 我在对带注释的 Aspect 类进行依赖注入时遇到了一些问题。CacheService 是在 Spring 上下文启动时注入的,但是当编织发生时,它说 cacheService 为空。所以我不得不手动重新查找 spring 上下文并从那里获取 bean。还有另一种方法吗?
这是我的方面的一个例子:
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import com.mzgubin.application.cache.CacheService;
@Aspect
public class CachingAdvice {
private static Logger log = Logger.getLogger(CachingAdvice.class);
private CacheService cacheService;
@Around("execution(public *com.mzgubin.application.callMethod(..)) &&"
+ "args(params)")
public Object addCachingToCreateXMLFromSite(ProceedingJoinPoint pjp, InterestingParams params) throws Throwable {
log.debug("Weaving a method call to see if we should return something from the cache or create it from scratch by letting control flow move on");
Object result = null;
if (getCacheService().objectExists(params))}{
result = getCacheService().getObject(params);
} else {
result = pjp.proceed(pjp.getArgs());
getCacheService().storeObject(params, result);
}
return result;
}
public CacheService getCacheService(){
return cacheService;
}
public void setCacheService(CacheService cacheService){
this.cacheService = cacheService;
}
}