导入包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
|
定义业务层方法
package com.jbit.service;
|
定义切面类
package com.jbit.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import java.util.Arrays;
@Aspect //告容器这是一个切面类。
public class LogAspects {
/**
* 抽取切入点表达式
* <li>本类引用:pointcut()</li>
* <li>其它类引用:com.jbit.config.pointcut()</li>
*/
@Pointcut("execution(public int com.jbit.service.Div.div(int,int))")
public void pointcut(){ }
@Before("pointcut()") //目标方法运行之前运行
public void logStart(JoinPoint joinPoint){
System.out.println(""+joinPoint.getSignature().getName()+"方法运行.......参数列表:{"+Arrays.asList(joinPoint.getArgs()) +"}");
}
@After("pointcut()")//目标方法运行之后(无论方法正常结束还是异常结束)
public void logEnd(JoinPoint joinPoint){
System.out.println(""+joinPoint.getSignature().getName()+"方法结束.......");
}
@AfterReturning(value="pointcut()",returning = "result") //返回通知
public void logReturn(JoinPoint joinPoint, Object result){
System.out.println(""+joinPoint.getSignature().getName()+"方法结果返回.......运行结果{"+result+"}");
}
@AfterThrowing(value = "pointcut()",throwing = "exception") //异常通知
public void logException(JoinPoint joinPoint,Exception exception){
System.out.println(""+joinPoint.getSignature().getName()+"方法异常.......异常结果{"+exception+"}");
}
// @Around(value = "pointcut()")
// public void logAround(JoinPoint joinPoint){
// System.out.println(""+joinPoint.getSignature().getName()+"运行.......@Around");
// }
}
|
装载IOC
package com.jbit.config;
import com.jbit.service.Div;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy//开启aop功能,启用基于注解的aop功能
public class Config {
@Bean //将要切入的类加入到容器中。
public Div div(){
return new Div();
}
@Bean //将切面类加入到容器中
public LogAspects logAspects(){
return new LogAspects();
}
}
|
测试
import com.jbit.service.Div;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class T {
@Test
public void test1() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(com.jbit.config.Config.class);
Div div = context.getBean(com.jbit.service.Div.class);
div.div(1,1);
}
} |