面向切面编程SpringAOP

  1. 注解方式实现aop,xml配置
名称空间xmlns:aop="http://www.springframework.org/schema/aop"
<context:component-scan base-package="tk.amrom"></context:component-scan>

<aop:aspectj-autoproxy>

</aop:aspectj-autoproxy>
  1. LogUtil.java

    ```java

@Aspect @Component public class LogUtil {

@Before(value = "execution(public int tk.amrom.impls.MyMathCaluctor.*(*, int))")
public static void logStart() {
    System.out.println("目标方法执行之前执行1。。。。。。");
}

@After(value = "execution(public int tk.amrom.impls.MyMathCaluctor.add(int, int)) | "
        + "execution(public int tk.amrom.impls.MyMathCaluctor.sub(int, int))")
public static void logAfter() {
    System.out.println("目标方法执行之后执行2。。。。。。。");
}

}

3. TestAOP.java
```java
public class TestAOP {
    ApplicationContext context = new ClassPathXmlApplicationContext("aop.xml");
    @Test
    public void test01() {
        Calcultor calcultor = context.getBean(Calcultor.class);
        calcultor.add(2, 3);
        calcultor.sub(3, 4);
    }
}
  1. JoinPoint使用
public void logBefore(JoinPoint j) {
    Object[] o = j.getArgs();
    System.out.println("目标方法执行之前执行1。。。。。。" + Arrays.asList(o));

}
  1. xml配置方式实现aop

aop.xml

<bean id="logUtilAspect" class="aspects.LogUtilAspect"></bean>

<aop:config>
    <aop:pointcut expression="execution(public int tk.amrom.impls.MyMathCaluctor.*(int, int))" id="mypointcut"/>

    <aop:aspect ref="logUtilAspect">
        <aop:before method="logBefore" pointcut-ref="mypointcut" />

    </aop:aspect>

</aop:config>
  1. 5大通知类型
<aop:before method="logBefore" pointcut-ref="mypointcut" />
<aop:after method=""/>
<aop:after-returning method=""/>
<aop:after-throwing method=""/>
<aop:around method=""/>