Spring 精华中aop的小测试

对aop进行了小测试,动手才能看清真相!


首先,写个aop中的target对象,


package com.xll.aop;

public class Target {
//...
public void work(){
System.out.println("我属于Target类且在Target中工作!");
}
//...
}



现在我写个target2:


package com.xll.aop;

public class Target2 {
public void work(){
System.out.println("work in the Target2.....");
}
}




然后写上我需要织入的advise(不知道这么描述是否正确,advise理解成我需要的横切关注点):


package com.xll.aop;

public class Advise {

public void weaveBefore(){
System.out.println("----before----");
}
public void weaveAfter(){
System.out.println("----after----");
}

}



然后在spring的主配置文件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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<bean id="myTarget" class="com.xll.aop.Target"></bean>
<bean id="myTarget2" class="com.xll.aop.Target2"></bean>
<bean id="myAdvise" class="com.xll.aop.Advise"></bean>


<aop:config>
<aop:aspect id="myAspect1" ref="myAdvise" ><!--ref为要切入的功能模块Aspect -->
<aop:pointcut id="myPoint"
expression="execution(* com.xll.aop.Target.*(..))"/>
<aop:before
pointcut-ref="myPoint"
method="weaveBefore"/> <!-- method是切入的功能模块Aspect中的方法 -->
</aop:aspect>

<aop:aspect id="myAspect2" ref="myAdvise" >
<aop:pointcut id="myPoint2"
expression="execution(* com.xll.aop.Target2.work(..))"/>
<aop:after
pointcut-ref="myPoint2"
method="weaveAfter"/>
</aop:aspect>

</aop:config>
</beans>



配置好后,编写我的单元测试:

package com.xll.aop;

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

import junit.framework.TestCase;

public class TestAop extends TestCase{


public void testAop(){
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
Target target = (Target)ctx.getBean("myTarget");
target.work();
}
}


测试结果:

----before----
我属于Target类且在Target中工作!



好了,织入成功!


现在修改我的测试:


public void testAop(){
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
Target2 target = (Target2)ctx.getBean("myTarget2");
target.work();
}



结果如下:

work in the Target2.....
----after----




对于AOP思想的理解,以后再补上,网上很多资源。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值