AOP概念
介绍
AOP是面向切面编程的技术,把一个个的横切关注点放到某个模块中去,称之为切面。那么每一个的切面都能影响业务的某一种功能,切面的目的就是功能增强,如日志切面就是一个横切关注点,应用中许多方法需要做日志记录的只需要插入日志的切面即可。(动态代理就可以实现 AOP),这种面向切面编程的思想就是 AOP 思想了。
相关术语
joinpoint连接点: 想加功能的 方法
pointcut切入点: 表达式,通过这个表达式可以看出来哪些类的哪些方法想加功能
advice:增强: 当拦截到joinpoint后,在方法的什么时机做什么增强 , 时机分为前置增强,后置增强
aspect切面: advice + pointcut , 也就是增强加切入点
target: 被代理的目标对象
weaving织入: 把advice加到target上之后,创建出proxy对象的过程
proxy: 一个类被aop织入增强后,产生的代理类
相关注解
@Component + @Aspext :
放在事务类上,定义切面
@Pointcut(“execution(* com.edt.service.impl.xxximpl.(…))”) :
定义切入点,贴在被定义的切入点方法(),随意定义一个空方法作为被定义的切入点方法
@Before(“被定义的切入点方法()”):
贴在开启事务方法
@AfterReturning(“被定义的切入点方法()”) :
贴在提交事务方法
@AfterThrowing(“被定义的切入点方法()”):
贴在回滚事务方法
案例演示
spring.xml中配置相关信息
//扫描包 使注解有效化
<context:component-scan base-package="com.edt.spring.aop"/>
//aop 注解解析器
<aop:aspectj-autoproxy/>
真实类
@Component
public class AopServiceImpl implements AopService {
@Override
public void save(String username, String password) {
System.out.println("保存了"+username+"密码为:"+password);
}
}
事务类(定义切面的)
@Component
@Aspect //定义切面
public class MyTransactionManager {
@Pointcut("execution(* com.edt.spring.aop.service.impl.AopServiceImpl.*(..))")
private void txPointcut(){//定义切入点
}
@Before("txPointcut()")
public void begin(){//定义增强时机
System.out.println("开启事务");
}
@AfterReturning("txPointcut()")
public void commit(){
System.out.println("提交事务");
}
@AfterThrowing("txPointcut()")
public void rollback(){
System.out.println("回滚事务");
}
}