AOP(Aspect Oriented Programming):动态代理
在程序运行期间将某段代码切入到指定方法指定位置进行运行的编程方式。
通知方法
- 前置通知:在目标方法运行之前运行
- 后置通知:在目标方法结束之后运行
- 返回通知:在目标方法正常返回之后运行
- 异常通知:在目标方法异常返回之后运行
- 环绕通知:动态代理,手动推进目标方法运行
AOP使用
逻辑类
package com.pickle.aop;
/**
* @author Pickle
* @version V1.0
* @date 2024/3/20 17:36
*/
public class MathCalculator {
public int div(int i, int j){
return i/j;
}
}
切面类
package com.pickle.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import java.util.Arrays;
/**
* 切面类
*
* @author Pickle
* @version V1.0
* @date 2024/3/20 17:47
*/
@Slf4j
@Aspect
public class LogAspects {
//抽取公共的切入点表达式
@Pointcut("execution(public * com.pickle.aop.MathCalculator.*(..))")
public void pointCut() {
}
//切入点表达式
@Before("pointCut()")
public void logStart(JoinPoint joinPoint) {
log.info(joinPoint.getSignature().getName() + "除法运行,参数列表{}", Arrays.asList(joinPoint.getArgs()));
}
@After("pointCut()")
public void logEnd(JoinPoint joinPoint) {
log.info(joinPoint.getSignature().getName() +"除法结束");
}
@AfterReturning(value = "pointCut()",returning = "result")
public void logReturn(Object result) {
log.info("除法正常返回,运行结果: {}",result);
}
@AfterThrowing(value = "pointCut()", throwing = "exception")
public void logException(Exception exception) {
log.info("除法异常返回,异常信息: {}",exception.getMessage());
}
}
加入IOC容器中
package com.pickle.config;
import com.pickle.aop.LogAspects;
import com.pickle.aop.MathCalculator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* @author Pickle
* @version V1.0
* @date 2024/3/20 11:30
*/
@Configuration
@EnableAspectJAutoProxy
public class PickleConfig {
//业务逻辑类添加到容器中
@Bean
public MathCalculator calculator() {
return new MathCalculator();
}
// 切面类加入容器中
@Bean
public LogAspects logAspects() {
return new LogAspects();
}
}
测试
@Test
void contextLoads() {
final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PickleConfig.class);
log.info("容器创建完成");
final MathCalculator calculator = (MathCalculator)context.getBean(MathCalculator.class);
calculator.div(1,1);
System.out.println(calculator);
}
标签:pickle,void,MathCalculator,AOP,import,com,public From: https://www.cnblogs.com/poteitoutou/p/18085778结果