spring之AOP初探

去面试Java绝对少不了的就是AOP(切面编程),我也纳闷,AOP就这么重要么,后来看了Spring实战之后发现,AOP就是Spring的很多特性的基础,日志记录,性能统计,安全控制,事务处理,异常处理等等。
这篇文章,我们简单的写一个demo体会一下AOP,后面我们再详细介绍。
还记得上一篇 讲了一个人类打电话的例子,既然是打电话,打之前少不了拨号的操作,打完之后少不了挂电话的操作。那我们就在打电话(call)的方法,这个切点上添加拨号和挂电话的操作。
为了演示切面操作,需要引入一个aspectj的包,在pom.xml里增加:

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.10</version>
        </dependency>

新增一个类电话操作类:

public class PhoneOperation {
    public void dial(){
        System.out.println("Dialing");
    }

    public void hangUp(){
        System.out.println("after hand up the phone");
    }
}

在resources/spring先新增一个新的aop.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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="phone" class="TelePhone">
    </bean>

    <bean name="human" class="ChaneseHuman">
        <property name="phone" ref="phone"/>
    </bean>

    <bean name="phoneOperation" class="PhoneOperation">
    </bean>
    <aop:config>
        <aop:aspect ref="phoneOperation">
            <aop:pointcut id="operation" expression="execution(* Phone*.call())"/>
            <aop:before method="dial" pointcut-ref="operation"/>
            <aop:after method="hangUp" pointcut-ref="operation"/>
        </aop:aspect>
    </aop:config>
</beans>

多了一个aop:config元素,这里不细讲aop:config元素有哪儿写操作,后续会讲解了。
修改我的main方法:

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/aop.xml");
        Human human = applicationContext.getBean(Human.class);
        human.call();

执行结果:

Dialing
I am calling by telephone!
after hand up the phone
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值