代理三要素:
1)被代理的目标
2)代理的增强类
3)增强类和目标的关联
SpringAOP需要引入的maven坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
一:给接口方法增加的通知切面类(增强类)
/ 在一个切面类,可以提供多个 advice方法
public class MyAspectJ {
// 环绕通知: 返回object
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Object returnVal = null;
try {
// 1 开启事务
System.out.println("================1 开启事务");
// 2 执行一组sql语句
returnVal = joinPoint.proceed();
// 3.1 提交事务
System.out.println("================2 提交事务");
} catch (Exception ex) {
ex.printStackTrace();
// 3.2 回滚事务
System.out.println("================3 回滚事务");
} finally {
// 4 释放资源
System.out.println("================4 释放资源");
}
return returnVal;
}
// 前置通知
public void before01(JoinPoint joinPoint) {
System.out.println("--------------------- 前置通知: 开启事务 ... ..." );
}
}
二:需要增加通知的接口(目标类)
public interface UserService {
public User findUserById(Long id);
public List<User> findUserAll();
public int deleteUserById(String id);
public int updateUser(User user);
public int addUser(User user);
}
三:spring配置文件增加aop配置使切面类与接口类绑定关系
<!--1 配置切面增强类-->
<bean id="myAspectJ" class="com.xucj.aspect.MyAspectJ"/>
<!--2 配置切入点和切面-->
<aop:config proxy-target-class="false">
<!--2.1 ref引入通知方法所在的类-->
<aop:aspect ref="myAspectJ">
<!--2.2 配置六种通知类型和切入点-->
<aop:pointcut id="myPointcut" expression="bean(*ServiceImpl)"/>
<!-- around:环绕通知,method:切面增强类增强的方法-->
<aop:around method="around" pointcut-ref="myPointcut"/>
<!--后置通知
<aop:after-returning method="afterRegurning" pointcut-ref="myPointcut" returning="returnObject"/>-->
<!--异常通知
<aop:after-throwing method="afterThrowing" pointcut-ref="myPointcut" throwing="ex"/>-->
<!--最终通知
<aop:after method="after" pointcut-ref="myPointcut" />-->
<!--前置通知
<aop:before method="before01" pointcut-ref="myPointcut"/>-->
</aop:aspect>
</aop:config>
四:测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringTest {
@Autowired
private UserService userService;
@Test
public void demo01() {
userService.findUserById(1L);
}
}
运行结果: