¼ÓÈëÊÕ²Ø | ÉèΪÊ×Ò³ | »áÔ±ÖÐÐÄ | ÎÒҪͶ¸å Àî´óͬ £¨https://www.lidatong.com.cn/£©- ¿Æ¼¼¡¢½¨Õ¾¡¢¾­Ñé¡¢ÔÆ¼ÆËã¡¢5G¡¢´óÊý¾Ý,Õ¾³¤Íø!
µ±Ç°Î»Ö㺠Ê×Ò³ > ´óÊý¾Ý > ÕýÎÄ

spring֮ΪʲôҪʹÓÃAOP£¨ÃæÏòÇÐÃæ±à³Ì£©£¿

·¢²¼Ê±¼ä£º2020-12-15 01:12:49 ËùÊôÀ¸Ä¿£º´óÊý¾Ý À´Ô´£ºÍøÂçÕûÀí
µ¼¶Á£ºÐèÇó1-ÈÕÖ¾£ºÔÚ³ÌÐòÖ´ÐÐÆÚ¼ä×·×ÙÕýÔÚ·¢ÉúµÄ»î¶¯£» ÐèÇó2-ÑéÖ¤£ºÏ£Íû¼ÆËãÆ÷Ö»´¦ÀíÕýÊýµÄÔËË㣻 Ò»¡¢ÆÕͨ·½·¨ÊµÏÖ Calculator.java package com.gong.spring.aop.helloworld; public interface Calculator { int add( int i, int j); int sub( int mul( int di

ÐèÇó1-ÈÕÖ¾£ºÔÚ³ÌÐòÖ´ÐÐÆÚ¼ä×·×ÙÕýÔÚ·¢ÉúµÄ»î¶¯£»

ÐèÇó2-ÑéÖ¤£ºÏ£Íû¼ÆËãÆ÷Ö»´¦ÀíÕýÊýµÄÔËË㣻

Ò»¡¢ÆÕͨ·½·¨ÊµÏÖ

Calculator.java

package com.gong.spring.aop.helloworld;

public interface Calculator {
    int add(int i,int j);
    int sub(int mul(int div( j);
}

CalculatorImpl.java

class CalculatorImpl implements Calculator{

    @Override
     j) {
        System.out.println("add begin");
        // TODO Auto-generated method stub
        int result =  i+j;
        System.out.println("add end"return result;
    }

    @Override
     j) {
        System.out.println("sub begin"int result = i - j;
        System.out.println("sub end" j) {
        System.out.println("mul begin"int result = i * j;
        System.out.println("mul end" j) {
        System.out.println("div begin"int result = i / j;
        System.out.println("div end" result;
    }

}

Main.java

class Main {
    static void main(String[] args) {
        Calculator calculator = new CalculatorImpl();
        int i = 2;
        int j = 1int res = calculator.add(i,j);
        System.out.println(res);
        res = calculator.sub(i,1)"> calculator.mul(i,1)"> calculator.div(i,j);
        System.out.println(res);
    }
}

Êä³ö£º

´æÔÚÁ½¸öÎÊÌ⣺

£¨1£©´úÂë»ìÂÒ£ºÃ¿¸ö·½·¨ÔÚ´¦ÀíÂß¼­ºËÐÄÎÊÌâʱ»¹Òª¹Ø×¢ÆäËüÎÊÌ⣬±ÈÈçÈÕÖ¾ºÍ¼ÆËã¡£

£¨2£©´úÂë·ÖÉ¢£ºÈç¹ûÈÕÖ¾·¢Éú±ä»¯£¬ÔòÐèÒªÐÞ¸ÄËùÓз½·¨µÄÈÕÖ¾¡£

¶þ¡¢µÚÒ»ÖÖ½â¾ö·½·¨£ºÊ¹Óö¯Ì¬´úÀí¡£

¶¯Ì¬´úÀíÔ­Àí£ºÊ¹ÓÃÒ»¸ö´úÀí½«¶ÔÏó°ü×°ÆðÀ´£¬È»ºóµ÷ÓøôúÀí¶ÔÏóÈ¡´úԭʼ¶ÔÏó£¬ÈκζÔԭʼ¶ÔÏóµÄµ÷Óö¼ÒªÍ¨¹ý´úÀí¡£´úÀí¶ÔÏó¾ö¶¨ÊÇ·ñÒÔ¼°ºÎʱ½«·½·¨×ªµ½Ô­Ê¼µÄ¶ÔÏóÉÏ¡£

CalculatorLoggingImpl.java

class CalculatorLoggingImpl  j) {
        j;
         j;
         result;
    }

}
import java.lang.reflect.InvocationHandler;
 java.lang.reflect.Method;
 java.lang.reflect.Proxy;

 CalculatorLoggingProxy {
    public CalculatorLoggingProxy(Calculator target) {
        this.target = target;
    }
    Òª´úÀíµÄ¶ÔÏó
    private Calculator target;
     Calculator getLoggingProxy() {
        Calculator proxy = null´úÀí¶ÔÏóÓÉÄÄÒ»¸öÀà¼ÓÔØÆ÷½øÐмÓÔØ
        ClassLoader loader = target.getClass().getClassLoader();
        ´úÀí¶ÔÏóµÄÀàÐÍ£¬¼´ÆäÖÐÓÐÄÄЩ·½·¨
        Class [] interfaces = new Class[]{Calculator.};
        µ÷ÓôúÀí¶ÔÏóÆäÖеķ½·¨Ê±£¬¸ÃÖ´ÐеĴúÂë
        InvocationHandler h =  InvocationHandler() {
            /*proxy:ÕýÔÚ·µ»ØµÄ´úÀí¶ÔÏó
             *method:£ºÕýÔÚ±»µ÷Óõķ½·¨
             *args£ºµ÷Ó÷½·¨Ê±´«ÈëµÄ²ÎÊý 
             * */
            @Override
            public Object invoke(Object proxy,Method method,Object[] args) throws Throwable {
                 TODO Auto-generated method stub
                String methodName = method.getName();
                ÈÕÖ¾
                System.out.println(methodName+" begin");
                Ö´Ðз½·¨
                Object result = method.invoke(target,args);
                ÈÕÖ¾
                System.out.println(methodName+" end" result;
            }
        };
        proxy = (Calculator) Proxy.newProxyInstance(loader,interfaces,h);
         proxy;
    }
}

Main.java

 CalculatorLoggingImpl();
        Calculator proxy =  CalculatorLoggingProxy(calculator).getLoggingProxy();
        int result =proxy.add(i,j);
        System.out.println(result);
        result = proxy.sub(i,1)"> proxy.mul(i,1)"> proxy.div(i,j);
        System.out.println(result);
    }
}

Êä³ö£º

¿ÉÒԴﵽͬÑùµÄЧ¹û£¬µ«ÊÇÎÒÃǵÄÈÕ־ģ¿éÖ»ÐèÒª¹Ø×¢ÔÚ´úÀíÖÐÈçºÎÐ޸쬽ø¶ø¿ÉÒÔÓ°Ïìµ½ÆÕͨʵÏÖµÄËùÓз½·¨¡£

Èý¡¢µÚ¶þÖÖ·½Ê½£ºÊ¹ÓÃAOP

AOPÊǶԴ«Í³OOP£¨ÃæÏò¶ÔÏó±à³Ì£©µÄÒ»ÖÖ²¹³ä¡£ÆäÖ÷Òª±à³Ì¶ÔÏóÊÇÇÐÃæ£¬¶øÇÐÃæÄ£¿é»¯ºáÇйØ×¢µã¡£ÔÚÓ¦ÓÃAOPʱ£¬ÈÔÈ»ÐèÒª¶¨Ò幫¹²¹¦ÄÜ£¬µ«¿ÉÒÔÃ÷È·¶¨ÒåÕâ¸ö¹¦ÄÜÔÚÄÄÀÒÔʲô·½Ê½Ó¦Óᣲ¢ÇÒ²»±ØÐÞ¸ÄÊÜÓ°ÏìµÄÀ࣬ÕâÑùÒ»À´ºáÇйØ×¢µã¾Í±»Ä£¿é»¯µ½ÌØÊâ¶ÔÏó£¨ÇÐÃæ£©Àï¡£

н¨Ò»¸ö°ü£¬Ä¿Â¼½á¹¹ÈçÏ£º

ÐèÒª¼ÓÈëµ½build pathÖеİü£º

˵Ã÷£º×¢½âÖеÄvalueÊôÐÔ±êʶÁËΪÄÄЩ·½·¨¼ÓÉÏ֪ͨ¡£

Calculator.java

 com.gong.spring.aop.impl;

 org.springframework.stereotype.Component;

@Component
 result;
    }

}

applicationContext.java

<?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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    
    context:component-scan base-package="com.gong.spring.aop.impl"></context:component-scan>
    <!-- ʹAspectJ×¢½âÆð×÷Óãº×Ô¶¯ÎªÆ¥ÅäµÄÀàÉú³É´úÀí¶ÔÏó -->
    aop:aspectj-autoproxy>
</beans>

?ÔÚLoggingAspect.javaÖÐÏÈÖ»¶¨ÒåÕâôһ¸öÀ࣬²¢ÇÒ¼ÓÉÏ×¢½â£º

 java.util.Arrays;
 java.util.List;

 javax.management.RuntimeErrorException;

 org.aspectj.lang.JoinPoint;
 org.aspectj.lang.ProceedingJoinPoint;
 org.aspectj.lang.annotation.After;
 org.aspectj.lang.annotation.AfterReturning;
 org.aspectj.lang.annotation.AfterThrowing;
 org.aspectj.lang.annotation.Around;
 org.aspectj.lang.annotation.Aspect;
 org.aspectj.lang.annotation.Before;
 org.springframework.stereotype.Component;

°ÑÕâ¸öÀàÉùÃ÷Ϊһ¸öÇÐÃæ£ºÐèÒª°Ñ¸ÃÀà·ÅÈëµ½IOCÈÝÆ÷ÖУ¬ÔÙÉùÃ÷Ϊһ¸öÇÐÃæ
@Aspect
@Component
 LoggingAspect {

}

Main.java£¨ÕâÀïÖ»²âÊÔÁ½¸ö£©

 org.springframework.context.ApplicationContext;
 org.springframework.context.support.ClassPathXmlApplicationContext;

 main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"´ÓIOCÈÝÆ÷ÖлñÈ¡beanµÄʵÀý
        Calculator calculator = (Calculator) ctx.getBean(Calculator.int res = calculator.add(2,1);
        System.out.println("ÔÚÖ÷º¯ÊýÖмӷ¨¼ÆËãµÄ½á¹û="+res);
        res = calculator.div(2,1)">);
        System.out.println("ÔÚÖ÷º¯ÊýÖгý·¨¼ÆËãµÄ½á¹û="+res);
    }
}

1.ǰÖÃ֪ͨ

ÔÚapplicationContext.javaÖÐÏȼÓÈ룺

    ÉùÃ÷¸Ã·½·¨ÎªÒ»¸öǰÖÃ֪ͨ£¬ÔÚÄ¿±ê·½·¨Ö®Ç°Ö´ÐÐ
    @Before("execution(public int com.gong.spring.aop.impl.Calculator.*(int,int))")
     beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println(methodName+" begin with "+args);
    }

Êä³ö£º

¼´Ç°ÖÃ֪ͨÊÇÔÚÄ¿±êº¯Êýµ÷ÓÃǰִÐС£

2.ºóÖÃ֪ͨ

ÔÙ¼ÓÈ룺

    ºóÖÃ֪ͨ£ºÔÚÄ¿±ê·½·¨Ö´Ðкó£¬ÎÞÂÛÊÇ·ñ·¢ÉúÒì³££¬Ö´ÐеÄ֪ͨ
    ÔÚºóÖÃ֪ͨÖв»ÄÜ·ÃÎÊÄ¿±êµÄÖ´Ðнá¹û
    @After("execution(public int com.gong.spring.aop.impl.Calculator.*(int,1)"> afterMethod(JoinPoint joinPoint) {
        »ñÈ¡Ãû×Ö
        String methodName = joinPoint.getSignature().getName();
        »ñÈ¡²ÎÊý
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println(methodName+" end with "+args);
    }

Êä³ö£º

ºóÖÃ֪ͨÔÚÄ¿±êº¯ÊýÖ´ÐкóÖ´ÐУ¬²¢ÇÒÎÞÂÛÄ¿±êº¯ÊýÊÇ·ñ³öÏÖÒì³££¬¶¼»áÖ´ÐС£ ¼ÙÉ轫³ý·¨·ÖĸÉèÖÃΪ0£¬ÄÇô½á¹ûΪ£º

3.´ø·µ»ØÖµµÄºóÖÃ֪ͨ

×¢Ê͵ô?afterMethod·½·¨£¬ÔÙ¼ÓÉÏ£º

    ÔÚ·½·¨Õý³£½áÊøºóÖ´ÐеĴúÂë
    ·µ»ØÍ¨ÖªÊÇ¿ÉÒÔ·ÃÎʵ½·½·¨µÄ·µ»ØÖµµÄ
    @AfterReturning(value="execution(public int com.gong.spring.aop.impl.Calculator.*(..))",returning="result" afterReturning(JoinPoint joinPoint,Object result) {
        String methodName = Arrays.asList(joinPoint.getArgs());
        System.out.println("ÔÚafterReturningµÃµ½·µ»ØÖµ£º"+ result);
        System.out.println(methodName+" end with "+args);
    }

Êä³ö£º

¿ÉÒÔÔÚ֪ͨº¯ÊýÀïÃæ»ñµÃ¼ÆËãµÄÖµ¡£

4.µ±·¢ÉúÒ쳣ʱ²Å»áÔËÐеÄ֪ͨ

»¹ÓÐÒ»ÖÖµ±Ö»Óз¢ÉúÒ쳣ʱ²Å»áÖ´ÐиÃ֪ͨ£º½«³ý·¨·Öĸ±äΪ0

    @AfterThrowing(value="execution(public int com.gong.spring.aop.impl.Calculator.*(..))" afterThrowing(JoinPoint joinPoint,Exception ex) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName+" occurs exception:"+ex);
    }

Êä³ö£º

5.»·ÈÆÍ¨Öª

    @Around(value="execution(public int com.gong.spring.aop.impl.Calculator.*(..))" Object aroundMethod(ProceedingJoinPoint pjd) {
        Object result = ;
        String methodName = pjd.getSignature().getName();
        Ö´ÐÐÄ¿±ê·½·¨
        try {
            ǰÖÃ֪ͨ
            System.out.println(methodName+" begin with "+Arrays.asList(pjd.getArgs()));
            Ö´ÐÐÄ¿±ê·½·¨
            result = pjd.proceed();
            ºóÖÃ֪ͨ
            System.out.println("ÔÚaroundMethodÖеõ½Öµ£º"+result);
        } catch (Throwable e) {
             TODO Auto-generated catch block
            Ò쳣֪ͨ
            System.out.println("the method occurs exception£º" + e);
            throw  RuntimeException(e);
        }
        ºóÖÃ֪ͨ
        System.out.println(methodName+" end with "+Arrays.asList(pjd.getArgs()));
         result;
    }

Êä³ö£º

µ±È»£¬ÔÚ»·ÈÆÍ¨ÖªÖÐÒ²Äܹ·´¦ÀíÒì³£¡£?

AOPµÄºÃ´¦£º

£¨1£©Ã¿¸öÊÂÎïÂß¼­Î»ÓÚÒ»¸öλÖ㬴úÂë²»·ÖÉ¢£¬±ãÓÚά»¤ºÍÉý¼¶£»

£¨2£©ÒµÎñÄ£¿é¸ü¼ò½à£¬Ö»°üº¬ºËÐÄÒµÎñ´úÂ룻

£¨±à¼­£ºÀî´óͬ£©

¡¾ÉùÃ÷¡¿±¾Õ¾ÄÚÈݾùÀ´×ÔÍøÂ磬ÆäÏà¹ØÑÔÂÛ½ö´ú±í×÷Õ߸öÈ˹۵㣬²»´ú±í±¾Õ¾Á¢³¡¡£ÈôÎÞÒâÇÖ·¸µ½ÄúµÄȨÀû£¬Ç뼰ʱÓëÁªÏµÕ¾³¤É¾³ýÏà¹ØÄÚÈÝ!

    ÍÆ¼öÎÄÕÂ
      ÈȵãÔĶÁ