Saturday, March 10, 2012

Code Policy Enforcement using AspectJ

AspectJ has a feature using which some of the architecture policies can be enforced in the codebase. This is the domain of static code analysis tools like PMD and Checkstyle, however AspectJ also can be a very good fit here, in providing a compile time feedback on any standard violations and if AJDT is integrated with Eclipse in providing an immediate feedback on violations to the developer .

Consider a simple rule that I had for one of my projects. I wanted to prevent @Cachable annotation to be used in the Controllers. A policy aspect enforcing this rule will look like this:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
public aspect NoCachingInController {
    declare error: execution(@RequestMapping @Cacheable * (@Controller *).*(..)) : "Contoller methods should not have the Cacheable annotation";

Now if anybody happens to add @Cacheable to the Controller methods would see the following in the Eclipse IDE with AJDT integrated:

And would see the following at the point of compilation:

No comments:

Post a Comment