spring-aop实现的两种方式,最近培训学的,学的比较浅,做个笔记记录一下

spring-aop
实现方法:
1.xml配置文件
2.注解

xml配置文件方式实现aop(通知类,被加强的实现类,)
1.编写通知类
//一共五种通知
2.配置xml文件
2.1)配置 需要加强的类 和 通知类 的注入 //标签
2.2)配置 切面aop:config</aop:config>
2.3)<aop:aspect ref="引入通知类"></aop:aspect>
2.4)配置切点(通知的生效范围)可精确到方法
<aop:pointcut id="pointCut" expression="execution(* ..(..))"/>
2.5)声明通知(before,after,after-returning,after-throwing,around),并引入切点
<aop:after-returning method="aferReturning" pointcut-ref="pointCut"/> //method必须和通知类内的方法名一样
3.调用
3.1)读取配置文件生成对象并放到容器中 new ClassPathXmlApplicationContext();
3.2)通过id从容器中取对象 getBean(id) //获取的是被加强类的对象
3.3)调用被加强类内的方法

注解的方式实现aop

// 在执行业务代码前做些操作,比如获取连接对象
@Before("execution(* com.spring.aop.test.UserServiceImpl*(..))")
public void before(){
System.out.println("before--------前置通知--------");
}

// 在执行业务代码后做些操作,无论是否发生异常,它都会执行,比如关闭连接对象
@After("execution(* com.spring.aop.test.UserServiceImpl*(..))")
public void after(){
System.out.println("after--------后置通知--------");
}

// 在执行业务代码后无异常,会执行的操作
@AfterReturning("execution(* com.spring.aop.test.UserServiceImpl*(..))")
public void afterReturning(){
System.out.println("after--------后置通知--------");
}

// 在执行业务代码后出现异常,需要做的操作,比如回滚事务
@AfterThrowing("execution(* com.spring.aop.test.UserServiceImpl*(..))")
public void afterThrowing(){
System.out.println("after--------后置通知--------");
}

@Around("execution(* com.spring.aop.test.UserServiceImpl*(..))")
public void around(){
    System.out.println("after--------环绕通知--------");
}
posted @ 2020-10-30 16:30  码农吊车尾  阅读(36)  评论(0)    收藏  举报