10.AOP学习

2019-03-09  本文已影响0人  王杰磊

AOP的概念

AOP的优势

AOP核心概念

AOP示例

package com.spring.aop;

public interface Move {
    public void move();
}
package com.spring.aop;

public class Tank implements Move {
    @Override
    public void move() {
        System.out.println("Tank is moving");
    }
}
package com.spring.aop;

public class TankProxy implements Move {
    private Move t;

    public TankProxy(Move t) {
        this.t = t;
    }

    @Override
    public void move() {
        System.out.println("start");
        t.move();
        System.out.println("stop");
    }
}
package com.spring.aop;

public class MoveApp {
    public static void main(String[] args) {
        Move t=new Tank();
        Move t1=new Car();
        Move moveproxy=new TankProxy(t);
        Move moveproxy1=new TankProxy(t1);
        moveproxy.move();
        moveproxy1.move();
    }
}

结果


image.png

AOP前置方法示例

package com.spring.aop;

public interface Hello {
    String getHello();
}
package com.spring.aop;

public class HelloImpl implements Hello {
    @Override
    public String getHello() {
        return "Hello,Spring AOP";
    }
}
package com.spring.aop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户自定义的前置增强类
 */
public class MyBeforeAdvice {
    private static final Logger logger= LoggerFactory.getLogger("Hello.class");
//    定义前置方法
    public void beforeMethod(){
        logger.info("错误");
        System.out.println("this is a before method");
    }
}
<!--配置一个Hello的bean,等同于Hello hello=new HelloImpl-->
    <bean id="hello" class="com.spring.aop.HelloImpl"/>
    <!--配置一个MyBeforeAdvice前置增强的bean-->
    <bean id="mybeforeadvice" class="com.spring.aop.MyBeforeAdvice"/>
    <!--进行AOP的配置-->
    <aop:config>
        <aop:aspect id="before" ref="mybeforeadvice">
            <aop:pointcut id="myPointCut" expression="execution(* com.spring.aop.*.*(..))"/>
            <aop:before method="beforeMethod" pointcut-ref="myPointCut"/>
        </aop:aspect>
    </aop:config>
package com.spring.aop;

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

public class HelloApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Spring.xml");
        Hello hello = context.getBean(Hello.class);
        System.out.println(hello.getHello());
    }
}

结果


image.png
上一篇下一篇

猜你喜欢

热点阅读