【Java】SpringAOP的使用

房东租房的例子

有一个房东要出租房屋:

package com.shin.demo04;

public class Host implements Rent {
    public void rent() {
        System.out.println("房东出租房屋");
    }
}
package com.shin.demo04;

public interface Rent {
    void rent();
}

在动态代理的例子中,已经可以实现通过一个代理生成类给各种各样的被代理类动态生成代理类了。但是从租房者的角度来看操作还是略复杂,不够透明。下面用SpringAOP来实现,先写个扩展功能类:

package com.shin.demo04;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Action implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("带你看房");
    }
}

然后写applicationContext.xml来配置:

<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <context:annotation-config/>

    <bean id="host" class="com.shin.demo04.Host"/>
    <bean id="action" class="com.shin.demo04.Action"/>

    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.shin.demo04.Host.*(..))"/>
        <aop:advisor advice-ref="action" pointcut-ref="pointcut"></aop:advisor>
    </aop:config>


</beans>

关于SpingAOP的概念和配置就不介绍了,这里的配置作用就是把action下的操作切入被代理类。具体切在哪里看Action实现了哪个接口。这里还要注意下execution表达式的语法。

有一个打工人前来租房:

package com.shin.demo04;

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

public class Client {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Rent host = context.getBean("host",Rent.class);
        host.rent();
    }
}

这时打工人不需要自己new任何对象了,从容器中拿个房东就可以租房了,从打工人的角度也看不到中介了。运行结果:
在这里插入图片描述

分析
  1. 跟动态代理的区别在哪?首先房东这个对象交给Spring来管理了,然后如果我们为房东配置了切面,那么Spring在创建房东的时候,实际上创建的是房东的代理对象。这也就是Rent host = context.getBean(“host”,Rent.class);中写的不是Host.class的原因。
  2. 几个要素:
    • 被代理的类
    • 被代理的类实现的接口
    • 切面类
    • spring配置bean和切面
    • 调用者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值