动态代理与SpringAOP

设计模式:代理模式

动态代理四步

  • 实现接口

  • 传入对象

  • 实现invoke方法

  • Proxy创建代理实例

public class DynamicProxy implements InvocationHandler {
    private Object target;

    public DynamicProxy(Object target) {
        this.target = target;
    }

    @Override
    //处理实例,返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("=》带租户看房子");
        Object obj = method.invoke(target, args);
        System.out.println("=》收中介费");
        return obj;
    }

    //生成得到代理对象
    public Object proxy(){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }
}

spring的aop实现

<!--
spirng实现aop
    方式1:
        创建一个普通类(切入类),创建执行功能的方法
        将切入类和服务类注册到spring的xml容器 
        配置aop
-->
<bean id="myPointCut2" class="com.example.pointCut.MyPointCut2"/>
    <aop:config>
        <aop:aspect ref="myPointCut2">
            <aop:pointcut id="point" expression="execution(* com.example.services.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

<!--方式2:注解实现
  导入业务bean和切面类,加入aspectj的注解。   切面类举例: @Aspect public class MyPointCut { @Before("execution(* com.example.services.UserServiceImpl.*(..))") public void before(){ System.out.println("日志:打印日志"); } @After("execution(* com.example.services.UserServiceImpl.*(..))") public void after(){ System.out.println("日志:打印日志"); } }
--> <!--注解--> <bean id="userServiceImpl" class="com.example.services.UserServiceImpl"/> <bean id="myPointCut" class="com.example.pointCut.MyPointCut"/> <aop:aspectj-autoproxy/>

 

posted @ 2021-06-01 19:12  你就是我  阅读(42)  评论(0编辑  收藏  举报