day04 Aop学习

2019-03-10  本文已影响0人  墨寒_3338

在运行时,动态地将代码切入到类的指定法、指定位置的编程思想就是AOP(面向切面编程)
AOP常用于编程中的事物,日志等。由代理机制实现

1.AOP核心概念

2.代理模式实例

建一个接口
public interface Move {
    void move();

}

继承接口的类
public class Tank implements Move{
    @Override
    public void move() {
        System.out.println("Tank is moving");
    }
}

创建代理类
public class Tankproxy implements Move{
    private Move t;
    public Tankproxy(Move t){
        this.t=t;
    }
    @Override
    public void move() {
        System.out.println("Starting");
        t.move();
        System.out.println("stop");
    }
}

main方法输出验证
public class MoveApp {
    public static void main(String[] args) {
        Tank tank=new Tank();
        Move moveProxy=new Tankproxy(tank);
        moveProxy.move();
    }
}

运行结果:

image.png

3.AOP实例

建一个接口
public interface Hello {
    String getHello();
}

继承接口的类
public class HelloImpl implements Hello{

    @Override
    public String getHello() {
        return "Hello,Spring AOP";
    }
}

AOP前置增强类
public class MyBeforeAdvice {
    //定义前置方法
    public void beforeMethod(){
        System.out.println("This is a before method");
    }
}

在xml文件中配置bean和aop
<?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="hello" class="com.spring.quickstart.HelloImpl"/>
       <bean id="advice" class="com.spring.quickstart.MyBeforeAdvice"/>
       <aop:config>
           <aop:aspect id="before" ref="advice">
                  <aop:pointcut id="myPointCut" expression="execution(* com.spring.quickstart.*.*(..))"/>
                  <aop:before method="beforeMethod" pointcut-ref="myPointCut"/>
           </aop:aspect>
       </aop:config>
</beans>

main方法类输出验证
public class HelloApp {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("/applicationContext.xml");
        Hello hello=context.getBean(Hello.class);
        System.out.println(hello.getHello());
    }

}

运行结果:

image.png
上一篇 下一篇

猜你喜欢

热点阅读