Issue
I've the following programs. The around method is getting called but why not the main method? As far as i know around method gets executed before or after the method execution. Here around method getting called but why it's not printing the main method i.e.,getEmploy();.
@Configuration
public class App extends Thread{
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.inno.aop");
context.refresh();
EmployManager emp = (EmployManager) context.getBean("employManager");
emp.getEmploy();
context.close();
}
}
@Service
public class EmployManager {
public void getEmploy() {
System.out.println("Here is your employ" );
}
public void getEmp() {
System.out.println("Here is your emp" );
}
}
@Aspect
@Component
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class EmployAspect {
@Around("execution(* com.inno.aop.EmployManager.*(..))")
public void logAround(JoinPoint joinPoint) {
System.out.println("Around method getting called");
}
}
Output:
Around method getting called
Solution
From the documentation
Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.
We need to use ProceedingJoinPoint
with @Around advice
org.aspectj.lang.ProceedingJoinPoint
Around advice is declared by using the @Around annotation. The first parameter of the advice method must be of type ProceedingJoinPoint. Within the body of the advice, calling proceed() on the ProceedingJoinPoint causes the underlying method to execute. The proceed method can also pass in an Object[]. The values in the array are used as the arguments to the method execution when it proceeds.
The code should be
@Around("execution(* com.inno.aop.EmployManager.*(..))")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Around method getting called");
joinPoint.proceed();
}
Answered By - R.G
Answer Checked By - Candace Johnson (JavaFixing Volunteer)