Spring基于注解配置(五)
Spring AOP
AOP:(动态代理)指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式
1.首先在pom.xml导入aop模块,Spring AOP:(spring-aspects),然后声明一个配置类,并加上@Configuration标识
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.21.RELEASE</version> </dependency>
@Configuration public class MainConfigOfAOP { }
2.声明一个类,在类里面写一个带参数有返回值的方法,并加上@Component标识
@Component public class MathCalculator { public int div(int i,int j) { return i/j; }//这里用除法方便测试异常情况 }
3.声明一个切面类,用@Component和@Aspect标识
@Component @Aspect //@Aspect:告诉Spring当前类是一个切面类 public class LogAspects { //抽取公共的切入点表达式 //1.本类引用pointCut() //2.其他的切面引用加上方法全名 @Pointcut("execution(public int com.spring.aop.MathCalculator.*(..))") public void pointCut() { } //@Before在目标方法之前切人,切入点表达式(指定在哪个方法切入)*所有..任意类型的参数 @Before("pointCut()") //JoinPoint 一定要放在参数表的第一位 public void logStart(JoinPoint joinPoint) { Object[] args = joinPoint.getArgs(); System.out.println(""+joinPoint.getSignature().getName()+"除法运行........参数列表是{"+Arrays.asList(args)+"}"); } @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="msg") public void ErrorReturn(JoinPoint joinPoint,Object msg) { System.out.println(""+joinPoint.getSignature().getName()+"除法异常返回.....异常信息:{"+msg+"}"); } }
通知方法:
前置通知:logStart(),在目标方法调用前执行@Before
后置通知:logEnd(),在目标方法调用后执行@After(无论方法正常结束还是异常结束)
返回通知:logReturn(),在目标方法正常返回之后执行@AfterReturning
异常通知:ErrorReturn(),在目标方法出现异常后执行@AfterThrowing
环绕通知,动态代理,手动推进目标方法运行(joinPoint.procced())@Around
4.在配置类上加上@ComponentScan("com.spring.aop")和@EnableAspectJAutoProxy
@EnableAspectJAutoProxy @Configuration @ComponentScan("com.spring.aop") public class MainConfigOfAOP { }
5.运行测试(首先测试异常情况)
public class MainTest_AOP { @Test public void testIOC() { //创建ioc容器 AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfAOP.class); MathCalculator bean = applicationContext.getBean(MathCalculator.class); bean.div(10, 0); applicationContext.close(); } }
结果如下:
div除法运行........参数列表是{[10, 0]}
div除法结束.....
div除法异常返回.....异常信息:{java.lang.ArithmeticException: / by zero}
接下来是正常情况:
bean.div(10, 2);
结果如下:
div除法运行........参数列表是{[10, 2]}
div除法结束.....
div除法正常返回.....运算结果5

浙公网安备 33010602011771号