AOP for all methods in the package

I am using AOP for the first time. I wrote below the AOP code, which works great when I use it to intercept a specific method.

Can someone guide me - how can I configure it to intercept all methods in a specific package (com.test.model)?

Basically how to configure appcontext.xml.

Also, do I need to do something like below to call before calling each method?

AopClass aoptest = (AopClass) _applicationContext.getBean("AopClass"); aoptest.addCustomerAround("dummy"); 

Can anyone help?

Please allow me if you need a few more explanations.

Below is my code:

Interface:

 package com.test.model; import org.springframework.beans.factory.annotation.Autowired; public interface AopInterface { @Autowired void addCustomerAround(String name); } 

Grade:

 package com.test.model; import com.test.model.AopInterface; import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Autowired; @Component public class AopClass implements AopInterface { public void addCustomerAround(String name){ System.out.println("addCustomerAround() is running, args : " + name); } } 

AOP:

 package com.test.model; import java.util.Arrays; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; @Aspect public class TestAdvice{ @Around("execution(* com.test.model.AopInterface.addCustomerAround(..))") public void testAdvice(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("testAdvice() is running!"); } } 

application context:

 <!-- Aspect --> <aop:aspectj-autoproxy /> <bean id="AopClass" class="com.test.model.AopClass" /> <bean id="TestAdvice" class="com.test.model.TestAdvice" /> 
+5
source share
1 answer

Just put:

 @Around("execution(* com.test.model..*.*(..))") 

Execution expression format:

 execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?) 

where only ret-type-pattern , name-pattern and param-pattern are required, so at least we need an expression like:

 execution(ret-type-pattern name-pattern(param-pattern)) 
  • ret-type-pattern matches return type, * for any
  • name-pattern matches the name of the method, you can use * as a wildcard and .. to specify a subpackage
  • param-pattern matches method parameters (..) for any number of parameters

Further information can be found here: 10. Aspect-oriented programming using Spring ; there are several useful examples .

+2
source

Source: https://habr.com/ru/post/1232426/


All Articles