ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring AOP

2019-06-23 14:53:29  阅读:139  来源: 互联网

标签:Spring void System proxy AOP println public out


一、原理

1、aop底层将采用代理机制进行实现。
2、接口 + 实现类 :spring采用 jdk 的动态代理Proxy。
3、实现类:spring 采用 cglib字节码增强。

二、术语

1、target:目标类,即需要被代理的类。例如:UserService
2、Joinpoint(连接点):所谓连接点是指那些可能被拦截到的方法。例如:所有的方法
3、PointCut 切入点:已经被增强的连接点。例如:addUser()
4、advice 通知/增强,增强代码。例如:after、before
5、Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.
6、proxy 代理类
7、Aspect(切面): 是切入点pointcut和通知advice的结合
       一个线是一个特殊的面。
      一个切入点和一个通知,组成成一个特殊的面。

三、手动实现方式(不使用Spring)

3.1 使用JDK动态代理

接口:

public interface UserService {
    void addUser();
    void updateUser();
    void deleteUser();
}

实现类:

public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("a_proxy a_jdk add user ... ");

    }

    @Override
    public void updateUser() {
        System.out.println("a_proxy a_jdk update user ... ");

    }

    @Override
    public void deleteUser() {
        System.out.println("a_proxy a_jdk delete user ... ");

    }

}

切面:

public class MyAspect {
    public void before(){
        System.out.println("jdk_proxy之目标方法执行前 ");
    }
    
    public void after(){
        System.out.println("jdk_proxy之目标方法执行后");
    }
    
}

工厂类创建代理对象:

public class MyBeanFactory {
    public static UserService createService(){
        final UserService userService = new UserServiceImpl();
        final MyAspect myAspect = new MyAspect();
        UserService proxy = (UserService) Proxy.newProxyInstance(
                MyBeanFactory.class.getClassLoader(), 
                userService.getClass().getInterfaces(),
                new InvocationHandler() {
                    
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args)
                            throws Throwable {
                        myAspect.before();
                        Object obj = method.invoke(userService, args);
                        myAspect.after();
                        
                        return obj;
                    }
                });
        return proxy;
    }
}

测试类:

public class TestJdkProxy {
    
    @Test
    public void demo01(){
        UserService userService = MyBeanFactory.createService();
        userService.addUser();
        userService.updateUser();
        userService.deleteUser();
    }
}

执行结果:

jdk_proxy之目标方法执行前 
a_proxy a_jdk add user ... 
jdk_proxy之目标方法执行后
jdk_proxy之目标方法执行前 
a_proxy a_jdk update user ... 
jdk_proxy之目标方法执行后
jdk_proxy之目标方法执行前 
a_proxy a_jdk delete user ... 
jdk_proxy之目标方法执行后
3.2 使用CGLIB字节码增强

 没有接口,只有实现类。
 采用字节码增强框架 cglib,在运行时 创建目标类的子类,从而对目标类进行增强。
需要导入整合了cglib.jar和asm.jar的spring-core..jar

目标类:

public class UserServiceImpl{

    public void addUser() {
        System.out.println("a_proxy b_cglib add user ... ");

    }

    public void updateUser() {
        System.out.println("a_proxy b_cglib update user ... ");

    }

    public void deleteUser() {
        System.out.println("a_proxy b_cglib delete user ... ");

    }

}

切面类:

public class MyAspect {
    public void before(){
        System.out.println("cglib之目标方法执行前");
    }
    
    public void after(){
        System.out.println("cglib之目标方法执行后 ");
    }
    
}
public class MyBeanFactory {
    
    public static UserServiceImpl createService(){
        //1 目标类
        final UserServiceImpl userService = new UserServiceImpl();
        //2切面类
        final MyAspect myAspect = new MyAspect();
        // 3.代理类 ,采用cglib,底层创建目标类的子类
        //3.1 核心类
        Enhancer enhancer = new Enhancer();
        //3.2 确定父类
        enhancer.setSuperclass(userService.getClass());
        /* 3.3 设置回调函数 , MethodInterceptor接口 等效 jdk InvocationHandler接口
         *  intercept() 等效 jdk  invoke()
         *      参数1、参数2、参数3:以invoke一样
         *      参数4:methodProxy 方法的代理
         *      
         * 
         */
        enhancer.setCallback(new MethodInterceptor(){

            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                
                //前
                myAspect.before();
                
                //执行目标类的方法
                Object obj = method.invoke(userService, args);
                // * 执行代理类的父类 ,执行目标类 (目标类和代理类 父子关系)
                methodProxy.invokeSuper(proxy, args);
                
                //后
                myAspect.after();
                
                return obj;
            }
        });
        //3.4 创建代理
        UserServiceImpl proxService = (UserServiceImpl) enhancer.create();
        
        return proxService;
    }

}

测试结果(将methodProxy.invokeSuper(proxy, args);注释即与jdk结果一致了):
(测试方法与jdk相同)

cglib之目标方法执行前
a_proxy b_cglib add user ... 
a_proxy b_cglib add user ... 
cglib之目标方法执行后 
cglib之目标方法执行前
a_proxy b_cglib update user ... 
a_proxy b_cglib update user ... 
cglib之目标方法执行后 
cglib之目标方法执行前
a_proxy b_cglib delete user ... 
a_proxy b_cglib delete user ... 
cglib之目标方法执行后 
AOP联盟通知
AOP联盟为通知Advice定义了org.aopalliance.aop.Advice,Spring按照通知Advice在目标类方法的连接点位置,可以分为5类:

• 前置通知 org.springframework.aop.MethodBeforeAdvice
• 在目标方法执行前实施增强
• 后置通知 org.springframework.aop.AfterReturningAdvice
• 在目标方法执行后实施增强
• 环绕通知 org.aopalliance.intercept.MethodInterceptor
• 在目标方法执行前后实施增强
• 异常抛出通知 org.springframework.aop.ThrowsAdvice
• 在方法抛出异常后实施增强
• 引介通知 org.springframework.aop.IntroductionInterceptor
• 在目标类中添加一些新的方法和属性

四、Spring编写代理:半自动

让spring 创建代理对象,从spring容器中手动的获取代理对象:
需要导入7个jar包:
(4+1)四个核心包(spring-beans、spring-context、spring-core、spring-expression)+logging
(1+1)AOP:AOP联盟aopalliance(规范)、spring-aop (实现)
目标类:

public interface UserService {
    public void addUser();
    public void updateUser();
    public void deleteUser();
}

切面类:

/**
 * 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
 * * 采用“环绕通知” MethodInterceptor
 *
 */
public class MyAspect implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        
        System.out.println("前3");
        
        //手动执行目标方法
        Object obj = mi.proceed();
        
        System.out.println("后3");
        return obj;
    }
}

xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 1 创建目标类 -->
    <bean id="userService" class="[包名].UserServiceImpl"></bean>
      <!-- 2 创建切面类 -->
    <bean id="myAspect" class="[包名].MyAspect"></bean>
        <!-- 3 创建代理类 
        * 使用工厂bean FactoryBean ,底层调用 getObject() 返回特殊bean
        * ProxyFactoryBean 用于创建代理工厂bean,生成特殊代理对象
            interfaces : 确定接口们
                通过<array>可以设置多个值
                只有一个值时,value=""
            target : 确定目标类
            interceptorNames : 通知 切面类的名称,类型String[],如果设置一个值 value=""
            optimize :强制使用cglib
                <property name="optimize" value="true"></property>
        底层机制
            如果目标类有接口,采用jdk动态代理
            如果没有接口,采用cglib 字节码增强
            如果声明 optimize = true ,无论是否有接口,都采用cglib
        
    -->

    <bean id="proxyService" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="interfaces" value="[包名].UserService"></property>
        <property name="target" ref="userService"></property>
        <property name="interceptorNames" value="myAspect"></property>
    </bean>
</beans>

测试类:

    @Test
    public void demo01(){
        String xmlPath = "[包名]/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        
        //获得代理类
        UserService userService = (UserService) applicationContext.getBean("proxyServiceId");
        userService.addUser();
        userService.updateUser();
        userService.deleteUser();
    }

总结:上面主要是让大家理解spring的原理,方便掌握Spring aop的实现。

五、spring aop编程:全自动

1、从spring容器获得目标类,如果配置aop,spring将自动生成代理。
2、要确定目标类、aspectj 切入点表达式,需导入jar包:aspectj.weaver.jar(一共8个jar包)
3、配置文件需要增加aop支持:
xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation=" http://www.springframework.org/schema/aop 
                     http://www.springframework.org/schema/aop/spring-aop.xsd">

完整的配置为:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 1 创建目标类 -->
    <bean id="userServiceId" class="[包名].UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="[包名].MyAspect"></bean>
    <!-- 3 aop编程 
        3.1 导入命名空间
        3.2 使用 <aop:config>进行配置
                proxy-target-class="true" 声明使用cglib代理(不声明,且目标类为接口+实现类,则默认为jdk动态代理)
            <aop:pointcut> 切入点 ,从目标对象获得具体方法
            <aop:advisor> 特殊的切面,只有一个通知 和 一个切入点
                advice-ref 通知引用
                pointcut-ref 切入点引用
        3.3 切入点表达式
            execution(* com.itheima.c_spring_aop.*.*(..))
            选择方法         返回值任意   包             类名任意   方法名任意   参数任意
        
    -->
    <aop:config proxy-target-class="true">
        <aop:pointcut expression="execution(* [包名].*.*(..))" id="myPointCut"/>
        <aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/>
    </aop:config>
</beans>

测试:

    @Test
    public void demo01(){
        String xmlPath = "com/itheima/c_spring_aop/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        
        //获得目标类
        UserService userService = (UserService) applicationContext.getBean("userServiceId");
        userService.addUser();
        userService.updateUser();
        userService.deleteUser();
    }

六、AspectJ通知类型

6种,知道5种(前置后置,环绕,抛出异常,最终),掌握1中(环绕),还有一种为引介:
before:前置通知(应用:各种校验)
    在方法执行前执行,如果通知抛出异常,阻止方法运行
afterReturning:后置通知(应用:常规数据处理)
    方法正常返回后执行,如果方法中抛出异常,通知无法执行
    必须在方法执行后才执行,所以可以获得方法的返回值。
around:环绕通知(应用:十分强大,可以做任何事情)
    方法执行前后分别执行,可以阻止方法的执行
    必须手动执行目标方法
afterThrowing:抛出异常通知(应用:包装异常信息)
    方法抛出异常后执行,如果方法没有抛出异常,无法执行
after:最终通知(应用:清理现场)
    方法执行完毕后执行,无论方法中是否出现异常

导入jar包(9个):(核心4+1)(aop 2(规范和实现))+1织入aspectj.weaver.jar+spring-aspects.jar

目标类为UserService与UserServiceImpl
切面类为:

public class MyAspect {
    
    public void myBefore(JoinPoint joinPoint){
        System.out.println("前置通知 : " + joinPoint.getSignature().getName());
    }
    
    public void myAfterReturning(JoinPoint joinPoint,Object ret){
        System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
    }
    
    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("前");
        //手动执行目标方法
        Object obj = joinPoint.proceed();
        
        System.out.println("后");
        return obj;
    }
    
    public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
        System.out.println("抛出异常通知 : " + e.getMessage());
    }
    
    public void myAfter(JoinPoint joinPoint){
        System.out.println("最终通知");
    }

}

配置:

<!-- 1 创建目标类 -->
    <bean id="userServiceId" class="[包名].UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="[包名].MyAspect"></bean>
    <!-- 3 aop编程 
        <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)
            ref 切面类引用
        <aop:pointcut> 声明一个切入点,所有的通知都可以使用。
            expression 切入点表达式
            id 名称,用于其它通知引用
    -->
    <aop:config>
        <aop:aspect ref="myAspectId">
            <aop:pointcut expression="execution(* [包名].UserServiceImpl.*(..))" id="myPointCut"/>
            
            <!-- 3.1 前置通知 
                <aop:before method="" pointcut="" pointcut-ref=""/>
                    method : 通知,及方法名
                    pointcut :切入点表达式,此表达式只能当前通知使用。
                    pointcut-ref : 切入点引用,可以与其他通知共享切入点。
                通知方法格式:public void myBefore(JoinPoint joinPoint){
                    参数1:org.aspectj.lang.JoinPoint  用于描述连接点(目标方法),获得目标方法名等
                例如:
            <aop:before method="myBefore" pointcut-ref="myPointCut"/>
            -->
            
            <!-- 3.2后置通知  ,目标方法后执行,获得返回值
                <aop:after-returning method="" pointcut-ref="" returning=""/>
                    returning 通知方法第二个参数的名称
                通知方法格式:public void myAfterReturning(JoinPoint joinPoint,Object ret){
                    参数1:连接点描述
                    参数2:类型Object,参数名 returning="ret" 配置的
                例如:
            <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />
            -->
            
            <!-- 3.3 环绕通知 
                <aop:around method="" pointcut-ref=""/>
                通知方法格式:public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
                    返回值类型:Object
                    方法名:任意
                    参数:org.aspectj.lang.ProceedingJoinPoint
                    抛出异常
                执行目标方法:Object obj = joinPoint.proceed();
                例如:
            <aop:around method="myAround" pointcut-ref="myPointCut"/>
            -->
            <!-- 3.4 抛出异常
                <aop:after-throwing method="" pointcut-ref="" throwing=""/>
                    throwing :通知方法的第二个参数名称
                通知方法格式:public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
                    参数1:连接点描述对象
                    参数2:获得异常信息,类型Throwable ,参数名由throwing="e" 配置
                例如:
            <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>
            -->
            <!-- 3.5 最终通知 -->           
            <aop:after method="myAfter" pointcut-ref="myPointCut"/>
        </aop:aspect>
    </aop:config>

仅有环绕通知的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
                    http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="userService" class="[包名].UserServiceImpl"></bean>
    <bean id="myAspect" class="[包名].MyAspect"></bean>
    
    <aop:config>
        <aop:aspect ref="myAspect">
            <aop:pointcut 
                expression="execution(* [包名].*.*(..))" 
                id="myPointCut"/>
            <aop:around method="myAround" pointcut-ref="myPointCut"/>
        </aop:aspect>
    </aop:config>
</beans>

七、基于注解

1、需要配置对包的扫描:
<context:component-scan base-package="com.itheima.d_aspect.b_anno"></context:component-scan>
2、两个bean可以用注解@Service("userService")与@Component来代替
3、必须进行aspectj自动代理

<!-- 2.确定 aop注解生效 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

4、声明切面
<aop:aspect ref="myAspectId">
用注解@Aspect代替

@Component
@Aspect
public class MyAspect{

5、前置通知

<aop:before method="myBefore" pointcut="execution(* [包名].UserServiceImpl.*(..))"/>
    //切入点当前有效
    @Before("execution(* [包名].UserServiceImpl.*(..))")
    public void myBefore(JoinPoint joinPoint){
        System.out.println("前置通知 : " + joinPoint.getSignature().getName());
    }

6、公共切入点

<aop:pointcut expression="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" id="myPointCut"/>
//声明公共切入点
    @Pointcut("execution(* [包名].UserServiceImpl.*(..))")
    private void myPointCut(){
    }

7、替换后置:(此处注解的value值相当于引用)

<aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />
    @AfterReturning(value="myPointCut()" ,returning="ret")
    public void myAfterReturning(JoinPoint joinPoint,Object ret){
        System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
    }

8、spring配置只需要:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
                    http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop.xsd
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 1.扫描 注解类 -->
    <context:component-scan base-package="com.jdwa.spring.d_aspect.b_anno"></context:component-scan>
    
    <!-- 2.确定 aop注解生效 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

9、切面类为:

@Component
@Aspect
public class MyAspect {
    
    //切入点当前有效
//  @Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
    public void myBefore(JoinPoint joinPoint){
        System.out.println("前置通知 : " + joinPoint.getSignature().getName());
    }
    
    //声明公共切入点
    @Pointcut("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
    private void myPointCut(){
    }
    
//  @AfterReturning(value="myPointCut()" ,returning="ret")
    public void myAfterReturning(JoinPoint joinPoint,Object ret){
        System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
    }
    
//  @Around(value = "myPointCut()")
    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("前");
        //手动执行目标方法
        Object obj = joinPoint.proceed();
        
        System.out.println("后");
        return obj;
    }
    
//  @AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")
    public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
        System.out.println("抛出异常通知 : " + e.getMessage());
    }
    
    @After("myPointCut()")
    public void myAfter(JoinPoint joinPoint){
        System.out.println("最终通知");
    }

}

大家有兴趣也可以关注我的公众号查看文章。

标签:Spring,void,System,proxy,AOP,println,public,out
来源: https://www.cnblogs.com/czz-hl/p/11072797.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有