简体   繁体   中英

Architectural Enforcement Using Spring/AspectJ

I have a Spring project uses annotations to apply (among other things) caching.

My understanding is that these annotations will only work when @Autowired and called through SpringAOP.

This means that if a method calls another in the same class, then any annotations on the second method are ignored eg

@Cacheable(...)
public Animal getAnimal(int id) {
    return get(m_url, id);
}

public Cage getCagedAnimal(int id) {
    Animal animal = getAnimal(id);  // This call will not apply @Cacheable
    Cage cagedAnimal = new Cage(animal);
    return cagedAnimal;
}

What I am looking for is a way to enforce against this ie public methods should not be able to call other public methods of the same class.

I tried applying something similar to the approach used here http://www.jayway.com/2010/03/28/architectural-enforcement-with-aid-of-aspectj but it falls short when applying the restriction on the same class.

It's perfectly doable, AspectJ is very powerful. But you seem to be using Spring AOP instead of AspectJ, and Spring AOP is quite limited compared to AspectJ. Spring AOP works by creating proxies around your actual bean implementation to implement the AOP features it provides. When the proxy gets the call, the advices will be applied and flow control will be passed to the normal bean. Should the normal bean (the target of the proxy) invoke another methods on itself, it won't be invoked on the proxy so the AOP part will be bypassed. AspectJ doesn't have that limitation as it's modifying your classes, not just creating proxies around them. I would strongly suggest to go with AspectJ instead of Spring AOP. Spring will work great with AspectJ too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM