1、引入依赖
<!--spring aop依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>6.0.2</version> </dependency> <!--spring aspects依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>6.0.2</version> </dependency>
2、定义接口和实现类
public interface Calculator { int add(int a,int b); int sub(int a,int b); int mul(int a,int b); int div(int a,int b); }
public class CalculatorImpl implements Calculator{ @Override public int add(int a, int b) { int res = a+b; System.out.println("res:"+res); return res; } @Override public int sub(int a, int b) { int res = a-b; System.out.println("res:"+res); return res; } @Override public int mul(int a, int b) { int res = a*b; System.out.println("res:"+res); return res; } @Override public int div(int a, int b) { int res = a/b; System.out.println("res:"+res); return res; } }
3、配置类
@Configuration @ComponentScan(value = "com.jixian") @EnableAspectJAutoProxy public class SpringConfig { }
4、切面类
@Aspect @Component public class AspectLog { @Before(value = "execution(public int com.jixian.CalculatorImpl.*(..))") public void beforeMethod(){ System.out.println("前置通知..."); } @After(value = "execution(* com.jixian.CalculatorImpl.*(..))") public void afterMethod(){ System.out.println("后置通知..."); } @AfterReturning(value = "execution(* com.jixian.CalculatorImpl.*(..))") public void afterReturn(){ System.out.println("返回通知..."); } @AfterThrowing(value = "execution(* com.jixian.CalculatorImpl.*(..))") public void throwMethod(){ System.out.println("异常通知..."); } @Around(value = "execution(* com.jixian.CalculatorImpl.*(..))") public Object aroundMethod(ProceedingJoinPoint joinPoint){ Object o = null; try { System.out.println("环绕通知...方法执行前"); o = joinPoint.proceed(); System.out.println("环绕通知...返回值后"); } catch (Throwable throwable) { throwable.printStackTrace(); System.out.println("环绕通知...出现异常"); } finally { System.out.println("环绕通知...方法执行后"); } return o; } }
5、测试
ApplicationContext context = new AnnotationConfigApplicationContext("com.jixian"); Calculator calculator = context.getBean(Calculator.class); calculator.div(12,1);
标签:基于,int,res,System,AOP,println,注解,public,out From: https://www.cnblogs.com/jixian/p/17161439.html