I. Introduction
Data in this chapter explain the use of Spring AOP
Second, open AOP
Spring AOP default is not open, you need via annotations @EnableAspectJAutoProxy. The comment function is to inject a Spring container components required AOP, implementation principle view
/** * 开启Spring AOP */ @EnableAspectJAutoProxy public class AopConfig { @Bean public Calculator calculator() { return new Calculator(); } @Bean public LogAop logAop() { return new LogAop(); } }
Third, the definition of the target object
Definition of the target object, and other objects there is no difference, so that the business code Spring AOP no invasive
public class Calculator { public int div(int num1, int num2) { return num1 / num2; } }
Fourth, the definition section
- @Aspect tell the Spring container which is a section
- @Pointcut need to define the target intercept method
- @Before target method before calling
- @After goal after execution method invocation
- @AfterReturning target method returns to the caller after execution
- @AfterThrowing target method throws an exception after calling
- @Around for @Before and @After, method calls can be manually controlled
@Aspect public class LogAop { @Pointcut("execution(* indi.zqc.spring.bean.Calculator.*(..))") public void pointcut() { } @Before(value = "pointcut()") public void before(JoinPoint joinPoint) { System.out.println("LogAop --- before --- " + joinPoint.getSignature().getDeclaringTypeName()); } @After(value = "pointcut()") public void after(JoinPoint joinPoint) { System.out.println("LogAop --- after --- " + joinPoint.getSignature().getDeclaringTypeName()); } @AfterReturning(value = "pointcut()", returning = "result") public void afterReturning(JoinPoint joinPoint, Object result) { System.out.println("LogAop --- afterReturning --- " + result); } @AfterThrowing(value = "pointcut()", throwing = "exception") public void afterThrowing(JoinPoint joinPoint, Exception exception) { System.out.println("LogAop --- afterThrowing --- " + exception); } @Around(value = "pointcut()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("LogAop --- around --- before"); // 调用目标方法 Object proceed = joinPoint.proceed(); System.out.println("LogAop --- around --- after"); return proceed; } }
Fifth, the target object, and poured into Spring container section
It must be cut and the target objects are injected into the Spring container, to take effect
Sixth, call
public class AopConfigTest { @Test public void test() { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AopConfig.class); Calculator calculator = applicationContext.getBean(Calculator.class); calculator.div(1, 1); } }