目录
SpringAOP:
AOP : 不通过修改源代码方式添加新的功能
专业术语:
1.连接点
类里面有哪些方法可以增强这些方法称为连接点,右边的几个方法当中谁可以被增强谁就是连接点
2.切入点
实际被增强的方法就是切入点,比如这四个方法都可以增强,但是我们只增强add0方法。那么add0方法就是切入点
3.通知(增强)
(1)实质增强的逻辑部分称为通知,就比如我们讲的登录逻辑当中的权限判断就是通知(增强)
(2)通知有多种类型
①:前置通知:在一个方法之前执行
②:后置通知:在-个方法执行完之后执行
③:环绕通知:在一个方法执行之前和之后都执行
④:异常通知:当一个方法发生异常的时候执行
⑤:最终通知:类似于finally最后永远执行
4.切面:是一个动作,将通知应用到切入点的过程
实现方式:Spring.xml 和注解两种方式
一、Spring.xml方式
①:和IOA一样,现在SPringle.xml文件中配置目标类
<bean id="login" class="com.test.Login"/>
<bean id="loginPower" class="com.test.LoginPower"/>
②创建目标类和增强方法:
public class Login {
public void login(){
System.out.println("登录判断");
}
}
public void 权限验证() {
System.out.println("权限判断成功");
}
③在Spring.xml中使用
<!--配置切面 = 切入点+通知-->
<aop:config>
<aop:aspect ref="loginPower">
<!--1.前置通知 method:通知的逻辑 pointcut:切入点-->
<!-- <aop:before method="权限验证" pointcut="execution(public void com.qcby.Login.login())"/>-->
<!--2.后置通知:after-returning-->
<!-- <aop:after-returning method="权限验证" pointcut="execution(public void com.qcby.Login.login())"/>-->
<!--3.异常通知:after-throwin-->
<!-- <aop:after-throwing method="权限验证" pointcut="execution(public void com.qcby.Login.login())"/>-->
<!--4.最终通知-->
<!-- <aop:after method="权限验证" pointcut="execution(public void com.qcby.Login.login())"/>-->
<!--5.环绕通知-->
<aop:around method="权限验证" pointcut="execution(public void com.qcby.Login.login())"/>
</aop:aspect>
</aop:config>
环绕通知比较特殊 要在增强方法中添加ProceedingJoinPoint joinPoint
@Around(value = "execution(public void com.test.Login.login())")
public void 权限验证(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("原方法之前执行");
//调用原方法:login方法
joinPoint.proceed();
System.out.println("原方法之后执行");
}
二、注解方式:
①、在Spring.xml中配置开启注解:
<!--开启注解扫描-->
<context:component-scan base-package="com.test"/>
<!--开启Aspect生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
②、目标类和增强方法加上注解:
import org.springframework.stereotype.Component;
@Component
public class Login {
public void login(){
System.out.println("登录判断");
}
}
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect//声明代理对象
public class LoginPower {
//前置通知:
//@Before(value = "execution(public void com.qcby.Login.login())")
//异常通知
//@AfterThrowing(value = "execution(public void com.qcby.Login.login())")
//最终通知
//@After(value = "execution(public void com.qcby.Login.login())")
/* //后置通知:
@AfterReturning(value = "execution(public void com.qcby.Login.login())")
public void berfore(){
System.out.println("before........");
}
*/
//环绕通知:
@Around(value = "execution(public void com.qcby.Login.login())")
public void 权限验证(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("原方法之前执行");
//调用原方法:login方法
joinPoint.proceed();
System.out.println("原方法之后执行");
}