Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 e.g.

@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 i.e. 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.

like image 324
Mike Avatar asked Aug 06 '26 08:08

Mike


1 Answers

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.

like image 79
Nándor Előd Fekete Avatar answered Aug 08 '26 22:08

Nándor Előd Fekete