5 aop spring dependency-injection aspectj load-time-weaving
使用Spring我在注释的Aspect类上进行依赖注入时遇到了一些问题.CacheService是在Spring上下文启动时注入的,但是当编织发生时,它表示cacheService为null.所以我不得不手动重新查看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;
}
}
Run Code Online (Sandbox Code Playgroud)
据我了解,问题在于 Spring 正在为您创建这种类型的 bean,但 AspectJ 框架也在创建这种类型的实例化,因为它不知道 Spring 已经这样做了。
我相信您想为 Spring 提供一个工厂方法来实例化 bean,同时让 AspectJ 知道 Aspect 已创建:
<!-- An @Aspect-annotated class -->
<bean id="bar" class="com.foo.bar" factory-method="aspectOf">
<property name="meaning" value="42" />
</bean>
Run Code Online (Sandbox Code Playgroud)
为了给予应有的信任,我今天早些时候遇到了这个问题,后来在其他地方找到了答案,所以我回来结束这个循环。
我不太清楚这里发生的魔法,但我确实看到有一个 Aspects 类提供了一些这种风格的静态构造函数。据推测,AspectJ 也将同名的静态方法编织到每个 Aspect 上以促进这种构造。
归档时间: |
|
查看次数: |
4875 次 |
最近记录: |