28 April, 2013

Operation Logic Executor - Spring Aspects

   I want to base my locking mechanism on Spring Aspects. So first lets shortly introduce simple example of using AOP. This aspect will be executed for all methods annotated with ResourceLock annotation.
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ResourceLock {
}
Next preparation step is to add spring-aspects artifact to dependencies from previous post.
   <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>3.2.2.RELEASE</version>
   </dependency>
Now I can implement aspect.
@Aspect
@Component
public class ResourceLockAspect {

    private Logger logger = LogManager.getLogger(ResourceLockAspect.class);

    @Around("@annotation(pl.mariusz.marciniak.locking.annotations.ResourceLock)")
    private Object execute(ProceedingJoinPoint pjp) throws Throwable {
        logger.debug("acquiring lock on "+ pjp.getArgs()[0]);
        pjp.proceed();
        logger.debug("releasing lock on "+ pjp.getArgs()[0]);
        return null;
    }
}
Around advice type means that advice surrounds method invocation. I will need that to lock resources and then release them after method execution is finished. As defined before pointcut expression will invoke advice for each method annotated with ResourceLock. So lets define bean with such a method.
@Component
public class ObjectUsingFakeLocking {

    private final Logger logger = LogManager.getLogger(ObjectUsingFakeLocking.class);

    public void executeNormalMethod(String parameter) {
        logger.info("executeNormalMethod - " + parameter);
    }

    @ResourceLock
    public void executeMethodLockingResources(String parameter) {
        logger.info("executeMethodLockingResources - " + parameter);

    }
}
Execution of both ObjectUsingFakeLocking methods
    private void testFakeLocking() {
        ObjectUsingFakeLocking obj = appContext.getBean(ObjectUsingFakeLocking.class);
        String param = "parameter";
        obj.executeNormalMethod(param);
        obj.executeMethodLockingResources(param);
        
    }
prints
19:40:34.192 [main] INFO  pl.mariusz.marciniak.locking.ObjectUsingFakeLocking - executeNormalMethod - parameter
19:40:34.198 [main] DEBUG pl.mariusz.marciniak.locking.aop.ResourceLockAspect - acquiring lock on parameter
19:40:34.198 [main] INFO  pl.mariusz.marciniak.locking.ObjectUsingFakeLocking - executeMethodLockingResources - parameter
19:40:34.198 [main] DEBUG pl.mariusz.marciniak.locking.aop.ResourceLockAspect - releasing lock on parameter
Okay, so my aspects work as desired. Next step is to combine it with asynchronous execution.

No comments:

Post a Comment