Extending a exception aspect in order to have application specific implementation - spring-boot

in my spring boot application, I have been using one external commons library for handling exceptions. The external library has an aspect defined for the same something like below:
#Aspect
#Order(0)
public class InternalExceptionAspect {
public InternalExceptionAspect() {
}
#Pointcut("#within(org.springframework.stereotype.Service)")
public void applicationServicePointcut() {
}
#AfterThrowing(
pointcut = "applicationServicePointcut()",
throwing = "e"
)
public void translate(JoinPoint joinPoint, Throwable e) {
String resourceId = this.getResourceId();
if (e instanceof BadInputException) {
BadInputException inputException = (BadInputException)e;
throw new BadRequestAlertException(inputException.getErrorCode().getDefaultMessage(), inputException.getMessage(), inputException.getErrorCode().getHttpStatusCode(), resourceId, inputException.getErrorCode().getCode());
} else if (!(e instanceof BadServerStateException) && !(e instanceof InternalException)) {
String message;
if (e instanceof JDBCException) {
...
throw new BadServerStateException(message, resourceId, "20");
} else {
...
throw new BadServerStateException(message, resourceId, "10");
}
} else {
InternalException serverStateException = (InternalException)e;
throw new BadServerStateException(serverStateException.getErrorCode().getDefaultMessage(), serverStateException.getMessage(), resourceId, serverStateException.getErrorCode().getHttpStatusCode(), serverStateException.getErrorCode().getCode(), serverStateException.getErrorCode().getErrorType().name());
}
}
String getResourceId() {
RequestHeaders requestHeaders = RequestResponseContext.getRequestHeaders();
return requestHeaders.getResourceId();
}
}
Here I would like to introduce another else if block in order to handle DuplicateKeyException for my application.
The problem is, the above code, being part of the commons library is being used by multiple other applications. But, I would like to do the change to be applied only in my application.
I have been thinking to inherit the Aspect class something like below, inside my application:
#Aspect
#Order(0)
public class MyInternalExceptionAspect extends InternalExceptionAspect {
public MyInternalExceptionAspect() {
}
#Pointcut("#within(org.springframework.stereotype.Service)")
public void applicationServicePointcut() {
}
#AfterThrowing(
pointcut = "applicationServicePointcut()",
throwing = "e"
)
public void translate(JoinPoint joinPoint, Throwable e) {
if(e instanceof DuplicateKeyException) {
...
}
super.translate(joinpoint, e);
}
}
But, I am not sure, if this is the correct approach to do this. Could anyone please help here regarding what would be the best approach to achieve this? Thanks.

You cannot extend a concrete aspect using class MyInternalExceptionAspect extends InternalExceptionAspect. It will cause an exception in Spring AOP:
...AopConfigException:
[...MyInternalExceptionAspect] cannot extend concrete aspect
[...InternalExceptionAspect]
Only abstract aspects are meant to be extended.
But you can simply create a new aspect without inheritance and make sure that it has a lower priority than the original aspect.
Why lower priority?
Acording to the #Order javadoc, "lower values have higher priority".
You want your own aspect's #AfterReturning advice to kick in before the original aspect possibly transforms the exception of interest into something else, before you have a chance to handle it. But according to the Spring manual: "The highest precedence advice runs first "on the way in" (so, given two pieces of before advice, the one with highest precedence runs first). "On the way out" from a join point, the highest precedence advice runs last (so, given two pieces of after advice, the one with the highest precedence will run second).".
Therefore, your own aspect should have #Order(1), giving it lower priority than the original aspect, but making the #AfterThrowing advide run before the original one. Sorry for the reverse logic, even though it makes sense. You just need to be aware of it.
Here is an MCVE, simulating your situation in a simplified way:
package de.scrum_master.spring.q69862121;
import org.springframework.stereotype.Service;
#Service
public class MyService {
public void doSomething(Throwable throwable) throws Throwable {
if (throwable != null)
throw throwable;
}
}
package de.scrum_master.spring.q69862121;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
#SpringBootApplication
#Configuration
public class DemoApplication {
private static final Logger log = LoggerFactory.getLogger(DemoApplication.class.getName());
public static void main(String[] args) throws Throwable {
try (ConfigurableApplicationContext appContext = SpringApplication.run(DemoApplication.class, args)) {
doStuff(appContext);
}
}
private static void doStuff(ConfigurableApplicationContext appContext) {
MyService myService = appContext.getBean(MyService.class);
List<Throwable> throwables = Arrays.asList(
null, // No exception -> no aspect should kick in
new Exception("oops"), // Not covered by any aspects -> no translation
new IllegalArgumentException("uh-oh"), // Original aspect translates to RuntimeException
new NullPointerException("null"), // Custom aspect translates to RuntimeException
new ArithmeticException("argh") // Custom aspect translates to IllegalArgumentException,
// then original aspect translates to RuntimeException
);
for (Throwable originalThrowable : throwables) {
try {
myService.doSomething(originalThrowable);
}
catch (Throwable translatedThrowable) {
log.info(translatedThrowable.toString());
}
}
}
}
As you can see, the application calls the service, the first time with null, not causing any exception, then with several types of exceptions the aspects are meant to either ignore or translate.
package de.scrum_master.spring.q69862121;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
#Aspect
#Component
#Order(0)
public class InternalExceptionAspect {
private static final Logger log = LoggerFactory.getLogger(InternalExceptionAspect.class.getName());
#AfterThrowing(pointcut = "#within(org.springframework.stereotype.Service)", throwing = "e")
public void translate(JoinPoint joinPoint, Throwable e) {
log.info(joinPoint + " -> " + e);
if (e instanceof IllegalArgumentException)
throw new RuntimeException("Transformed by InternalExceptionAspect", e);
}
}
package de.scrum_master.spring.q69862121;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
#Aspect
#Component
#Order(1)
public class MyInternalExceptionAspect {
private static final Logger log = LoggerFactory.getLogger(MyInternalExceptionAspect.class.getName());
#AfterThrowing(pointcut = "#within(org.springframework.stereotype.Service)", throwing = "e")
public void translate(JoinPoint joinPoint, Throwable e) {
log.info(joinPoint + " -> " + e);
if (e instanceof NullPointerException)
throw new RuntimeException("Transformed by MyInternalExceptionAspect", e);
if (e instanceof ArithmeticException)
throw new IllegalArgumentException("Transformed by MyInternalExceptionAspect", e);
}
}
The console log proves that everything works as expected, also with regard to invocation order:
d.s.s.q.MyInternalExceptionAspect : execution(void de.scrum_master.spring.q69862121.MyService.doSomething(Throwable)) -> java.lang.Exception: oops
d.s.s.q69862121.InternalExceptionAspect : execution(void de.scrum_master.spring.q69862121.MyService.doSomething(Throwable)) -> java.lang.Exception: oops
d.s.spring.q69862121.DemoApplication : java.lang.Exception: oops
d.s.s.q.MyInternalExceptionAspect : execution(void de.scrum_master.spring.q69862121.MyService.doSomething(Throwable)) -> java.lang.IllegalArgumentException: uh-oh
d.s.s.q69862121.InternalExceptionAspect : execution(void de.scrum_master.spring.q69862121.MyService.doSomething(Throwable)) -> java.lang.IllegalArgumentException: uh-oh
d.s.spring.q69862121.DemoApplication : java.lang.RuntimeException: Transformed by InternalExceptionAspect
d.s.s.q.MyInternalExceptionAspect : execution(void de.scrum_master.spring.q69862121.MyService.doSomething(Throwable)) -> java.lang.NullPointerException: null
d.s.s.q69862121.InternalExceptionAspect : execution(void de.scrum_master.spring.q69862121.MyService.doSomething(Throwable)) -> java.lang.RuntimeException: Transformed by MyInternalExceptionAspect
d.s.spring.q69862121.DemoApplication : java.lang.RuntimeException: Transformed by MyInternalExceptionAspect
d.s.s.q.MyInternalExceptionAspect : execution(void de.scrum_master.spring.q69862121.MyService.doSomething(Throwable)) -> java.lang.ArithmeticException: argh
d.s.s.q69862121.InternalExceptionAspect : execution(void de.scrum_master.spring.q69862121.MyService.doSomething(Throwable)) -> java.lang.IllegalArgumentException: Transformed by MyInternalExceptionAspect
d.s.spring.q69862121.DemoApplication : java.lang.RuntimeException: Transformed by InternalExceptionAspect

Related

Why can't Spring AOP determine if proxy should be made for #target? [duplicate]

When using spring AOP with class level annotations, spring context.getBean seems to always create and return a proxy or interceptor for every class, wether they have the annotation or not.
This behavior is only for class level annotation. For method level annotations, or execution pointcuts, if there is no need for interception, getBean returns a POJO.
Is this a bug? As designed? Or am I doing something wrong?
#Component
#Aspect
public class AspectA {
#Around("#target(myAnnotation)")
public Object process(ProceedingJoinPoint jointPoint, MyAnnotation myAnnotation) throws Throwable {
System.out.println(
"AspectA: myAnnotation target:" + jointPoint.getTarget().getClass().getSimpleName());
System.out.println(" condition:" + myAnnotation.condition());
System.out.println(" key:" + myAnnotation.key());
System.out.println(" value:" + myAnnotation.value());
return jointPoint.proceed();
}
}
#Component("myBean2")
//#MyAnnotation(value="valtest-classLevel2", key="keytest-classLevel2", condition="contest-classLevel2")
public class MyBean2 {
public Integer testAspectCallInt(int i) {
System.out.println("MyBean2.testAspectCallInt(i=" + i + ")");
return i + 1000;
}
}
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.TYPE, ElementType.METHOD })
public #interface MyAnnotation {
String value() default "";
String key() default "";
String condition() default "";
}
#ComponentScan()
#EnableAspectJAutoProxy
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(Test.class);
MyBean2 bean = (MyBean2) ctx.getBean("myBean2");
System.out.println(bean.getClass()); // prints CGLIB proxy, even when annotation is commented out on class
bean.testAspectCallInt(12); // calling method
}
}
Andy Brown is right, it is by design. The reason is that according to the AspectJ manual pointcut designators such as #args, #this, #target, #within, #withincode, and #annotation (or the subset of those available in Spring AOP) are used to match based on the presence of an annotation at runtime. This is why in the Spring debug log you see that proxies are created for all components which might need aspect functionality.
If you want to avoid that, you can refactor your aspect into something like this at the cost of an uglier pointcut and even uglier reflection in the advice code:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
#Component
#Aspect
public class AspectA {
#Around("execution(* (#MyAnnotation *).*(..)) || execution(#MyAnnotation * *(..))")
public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
MyAnnotation myAnnotation = null;
for (Annotation annotation : ((MethodSignature) joinPoint.getSignature()).getMethod().getDeclaredAnnotations()) {
if (annotation instanceof MyAnnotation) {
myAnnotation = (MyAnnotation) annotation;
break;
}
}
if (myAnnotation == null) {
myAnnotation = joinPoint.getTarget().getClass().getAnnotationsByType(MyAnnotation.class)[0];
}
System.out.println("AspectA: myAnnotation target:" + joinPoint.getTarget().getClass().getSimpleName());
System.out.println(" condition:" + myAnnotation.condition());
System.out.println(" key:" + myAnnotation.key());
System.out.println(" value:" + myAnnotation.value());
return joinPoint.proceed();
}
}
If neither the bean's class nor any of its methods bears the annotation, no proxy will be created. The advice detects both types of annotation, but prefers a method annotation if both are present.
Update: Instead of this workaround you could of course use full AspectJ from within Spring and avoid proxies altogether.

Azure Service Bus - Spring Boot disable autostart (com.microsoft.azure : azure-servicebus-spring-boot-starter)

I have the following implementation to consume the message from Azure Service Bus using Spring Boot application however I want to be able to control the ServiceBusConsumer from automatically start listening to the Topic using Spring boot profile property
something like this in the application.yaml
servicebus.consumer.enable=false
it should disable the ServiceBusConsumer from listening to the Topic(s) as well as I should be able to start the ServiceBusConsumer using a REST API - eg: ./api/servicebus/consumer/start?
import com.microsoft.azure.servicebus.ExceptionPhase;
import com.microsoft.azure.servicebus.IMessage;
import com.microsoft.azure.servicebus.IMessageHandler;
import com.microsoft.azure.servicebus.ISubscriptionClient;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
#Log4j2
#Component
class ServiceBusConsumer implements Ordered {
private final ISubscriptionClient iSubscriptionClient;
ServiceBusConsumer(ISubscriptionClient isc) {
this.iSubscriptionClient = isc;
}
#EventListener(ApplicationReadyEvent.class)
public void consume() throws Exception {
this.iSubscriptionClient.registerMessageHandler(new IMessageHandler() {
#Override
public CompletableFuture<Void> onMessageAsync(IMessage message) {
log.info("received message " + new String(message.getBody()) + " with body ID " + message.getMessageId());
return CompletableFuture.completedFuture(null);
}
#Override
public void notifyException(Throwable exception, ExceptionPhase phase) {
log.error("eeks!", exception);
}
});
}
#Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
You can create the ServiceBusConsumer bean conditionally by adding the #ConditionalOnProperty annotation like so, to make sure the bean is created only when servicebus.consumer.enabled=true:
#Log4j2
#Component
#ConditionalOnProperty(prefix = "servicebus.consumer", name = "enabled")
class ServiceBusConsumer implements Ordered {
...
}

spring-boot- #AfterThrowing is not executing advice method though exception is thrown?

I am new to Spring-boot and AOP. I am trying to log the exceptions raised in my spring-boot application. What exactly i am trying to do is whenever any method in my application classes raises the runtime exception, i am logging it to console.
So i created an aspect with #AfterThrowing annotation. To check whether it is working i have intentionally written a line of code which will raise / by zero exception. I tested with it but this advice method is not working.
Following is my test code:
package com.sware.SpringBoot_JPA_MySQL_Gradle_Project.aspects;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.sware.SpringBoot_JPA_MySQL_Gradle_Project.domains.User;
#Aspect
#Component
public class UserAspect {
#Before("execution(* com.sware.SpringBoot_JPA_MySQL_Gradle_Project.services.UserService.saveUserToDb(com.sware.SpringBoot_JPA_MySQL_Gradle_Project.domains.User)) && args(user)")
public void beforeUserSave(User user) {
System.out.println("++++++++++++++++++++++++++++++Creating UserBefore Pointcut: \n"+user.toString());
}
#After("execution(* com.sware.SpringBoot_JPA_MySQL_Gradle_Project.services.UserService.saveUserToDb(com.sware.SpringBoot_JPA_MySQL_Gradle_Project.domains.User)) && args(user)")
public void aftereUserSave(User user) {
System.out.println("++++++++++++++++++++++++++++++Creating User After pointcut: \n"+user.toString());
}
#AfterThrowing(pointcut = "execution(* com.sware.SpringBoot_JPA_MySQL_Gradle_Project.services.*.*(..))", throwing = "e")
public void myAfterThrowing(JoinPoint joinPoint, Throwable e) {
System.out.println("Okay - we're in the handler...");
/*Signature signature = joinPoint.getSignature();
String methodName = signature.getName();
String stuff = signature.toString();
String arguments = Arrays.toString(joinPoint.getArgs());
System.out.println("**************************EXCEPTION: "
+ methodName + " with arguments "
+ arguments + "\nand the full toString: " + stuff + "\nthe exception is: "
+ e.getMessage());*/
}
}
i have tried multiple permutations of pointcut expression like bellow,but no one works:
#AfterThrowing(pointcut = "execution(* com.sware.SpringBoot_JPA_MySQL_Gradle_Project.services.*.*(..))", throwing = "e")
#AfterThrowing(pointcut = "execution(* *.*(..))", throwing = "e") // Application fails to start throws some internal null pointer exception
#AfterThrowing(pointcut = "execution(* com.sware.*.*.*.*(..))", throwing = "e")
My Class Code:
package com.sware.SpringBoot_JPA_MySQL_Gradle_Project.services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sware.SpringBoot_JPA_MySQL_Gradle_Project.domains.User;
import com.sware.SpringBoot_JPA_MySQL_Gradle_Project.projections.UserWithFnameAndLname;
import com.sware.SpringBoot_JPA_MySQL_Gradle_Project.repositories.UserRepository;
#Service
public class UserService {
#Autowired
UserRepository userRepository;
public List<User> getAllUsers(){
List<User> userList=new ArrayList<>();
try {
Integer n=10/0;
userList=userRepository.findAll();
} catch (Exception e) {
System.out.println("Exception in UserRepostory:"+e.getMessage());
}
return userList;
}
}
Here, myAfterThrowing method is not getting call though /by zero is thrown at run time. Can anyone tell me where i am going wrong?
Method does not not throw any exception. The "try-catch" block basically absorbs the exception. Move "Integer n=10/0;" outside of the try-catch

Register beforeCommit callback for all Spring managed transactions

I am using the ChainedTransactionManager to implement Best Effort 1PC across ActiveMQ and MySQL, in my case the Database transaction commits first. In order to reduce the window of failure I want to check whether the ActiveMQConnection has failed just before committing the database transaction. I can do this once a transaction has started with the TransactionSynchronizationManager.registerSynchronization, but what I want is to register a block of code that runs for every transaction without having to do it in my code.
I could just subclass the ChainedTransactionManager but this does not seem the cleanest. Is there a better way to do this?
EDIT: Looks like subclassing ChainedTransactionManager is not a good idea as it relies on MultiTransactionStatus which is not public. Creating a new PlatformTransactionManager that delegates to a ChainedTransactionManager is an alternative.
This is how I have decided to implement it:
import org.apache.activemq.ActiveMQConnection;
import org.springframework.data.transaction.ChainedTransactionManager;
import org.springframework.jms.connection.JmsResourceHolder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public class JmsTransportFailureHandlingTransactionManager implements PlatformTransactionManager {
private final ChainedTransactionManager chainedTransactionManager;
public JmsTransportFailureHandlingTransactionManager(ChainedTransactionManager chainedTransactionManager) {
this.chainedTransactionManager = chainedTransactionManager;
}
#Override
public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
TransactionStatus transaction = chainedTransactionManager.getTransaction(definition);
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
#Override
public void beforeCommit(boolean readOnly) {
for (Object resource : TransactionSynchronizationManager.getResourceMap().values()) {
if (resource instanceof JmsResourceHolder) {
ActiveMQConnection connection = (ActiveMQConnection) ((JmsResourceHolder) resource).getConnection();
if (connection.isTransportFailed()) {
throw new IllegalStateException("ActiveMQ transport failed.");
}
}
}
}
});
return transaction;
}
#Override
public void commit(TransactionStatus status) throws TransactionException {
chainedTransactionManager.commit(status);
}
#Override
public void rollback(TransactionStatus status) throws TransactionException {
chainedTransactionManager.rollback(status);
}
}

How do I pass arguments to Spring AOP advice with annotated parameters?

I am using Spring 3.1.2.RELEASE with cglib load-time weaving and I am trying to get advice to work with a method that has custom annotations and annotated parameters.
Advice:
#Aspect
public class MyAdvice
{
#Around("execution(#com.mycompany.locking.Lock * *(#com.mycompany.locking.LockVal(*), ..)) " +
"&& args(batch) && #args(propertyToLock)"
public Object lockAndProceed(ProceedingJoinPoint pjp, Object batch, LockVal propertyToLock) throws Throwable {
//Do stuff....
pjp.proceed();
}
}
Here is the class that I am testing:
public interface UpdateManager
{
public void processUpdate(MyBatchObject batch);
}
public class UpdateManagerImpl implements UpdateManager
{
#Lock
public void processUpdate(#LockVal("lockValue") MyBatchObject batch)
{
//Do stuff...
}
}
The problem is that I can't get the advice to execute. If I remove the #args and args conditions in the pointcut, the advice fires, but then I have to dig through the ProceedingJoinPoint to get the parameter that I need.
Why isn't the advice firing? Did I do something wrong?
Edit: The following pointcut DOES WORK as a standalone program with Spring:
#Aspect
public class MyAdvice
{
#Around("execution(#com.mycompany.locking.Lock * *(#com.mycompany.locking.LockVal(*), ..)) " +
"&& args(batch)"
public Object lockAndProceed(ProceedingJoinPoint pjp, Object batch) throws Throwable {
//Do stuff....
pjp.proceed();
}
}
However, it does NOT work under JBoss 6 using load-time weaving. I suppose my question should be, then, why does it work as a standalone program but not under JBoss 6?
Update: I forgot to mention that #args() is not meant to match a parameter's annotation, but a parameter type's annotation, which is not what you want and which thus I do not use here.
You cannot bind a parameter's annotation via args(), only the parameter itself. This means that you can only access the parameter's annotation via reflection. You need to determine the method signature, create a Method object from it and then iterate over the method parameters' annotations. Here is a full code sample:
package com.mycompany.locking;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface Lock {}
package com.mycompany.locking;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.PARAMETER)
public #interface LockVal {
String value() default "";
}
package com.mycompany;
public class MyBatchObject {}
package com.mycompany;
public interface UpdateManager {
public void processUpdate(MyBatchObject batch);
}
package com.mycompany;
import com.mycompany.locking.Lock;
import com.mycompany.locking.LockVal;
public class UpdateManagerImpl implements UpdateManager {
#Lock
#Override
public void processUpdate(#LockVal("lockValue") MyBatchObject batch) {
System.out.println("Processing update");
}
public static void main(String[] args) {
UpdateManager updateManager = new UpdateManagerImpl();
updateManager.processUpdate(new MyBatchObject());
}
}
package com.mycompany.aop;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import com.mycompany.MyBatchObject;
import com.mycompany.locking.LockVal;
#Aspect
public class MyAspect {
#Pointcut("execution(#com.mycompany.locking.Lock * *(#com.mycompany.locking.LockVal (*), ..)) && args(batch)")
public void lockedMethod(MyBatchObject batch) {}
#Around("lockedMethod(batch)")
public Object lockAndProceed(ProceedingJoinPoint pjp, MyBatchObject batch) throws Throwable {
System.out.println(pjp);
System.out.println(batch);
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
Class<?> clazz = methodSignature.getDeclaringType();
Method method = clazz.getDeclaredMethod(methodSignature.getName(), methodSignature.getParameterTypes());
LockVal propertyToLock;
for (Annotation ann : method.getParameterAnnotations()[0]) {
if(LockVal.class.isInstance(ann)) {
propertyToLock = (LockVal) ann;
System.out.println(propertyToLock.value());
}
}
return pjp.proceed();
}
}
When I run UpdateManagerImpl.main, I see the following output, just as expected:
execution(void com.mycompany.UpdateManagerImpl.processUpdate(MyBatchObject))
com.mycompany.MyBatchObject#86f241
lockValue
Processing update
Disclaimer: I am not a Spring guy, I just tested this with plain AspectJ, not Spring AOP.
This is not a solution, but should take you a step further:
I am assuming you made a typo in your annotations, you probably meant #Aspect and not #Advice?
The suggestion that I have would be to try out these:
a. Separate out into named point cuts and the advice that you want to apply on the pointcut:
#PointCut("execution(#com.mycompany.locking.Lock * *(#com.mycompany.locking.LockVal(*), ..)) && args(batch) && #args(propertyToLock)")
public void mypointcut(Object batch, LockVal propertyToLock){}
#Around("mypointcut(batch, propertyToLock)"
public Object lockAndProceed(ProceedingJoinPoint pjp, Object batch, LockVal propertyToLock) throws Throwable {
//Do stuff....
pjp.proceed();
}
b. It could be that either args expression or #args expression is causing the issue - try keeping one and removing other and seeing which combination works.
c. If this does not narrow things down, one more option could be to explicitly add an argNames expression also, it could be that the argument names are being cleaned out and not being matched up by name at runtime:
#PointCut("execution(#com.mycompany.locking.Lock * *(#com.mycompany.locking.LockVal(*), ..)) && args(batch) && #args(propertyToLock) && argNames="batch,test1,test2")
public void mypointcut(Object batch, LockVal propertyToLock){}

Resources