Spring aop 小实例demo

 

因为近期提供接口服务项目中要有个需求,所有的操作必须检查一下服务是否可用的动作,所以感觉Aop实现起来特别合适,整理学习一下小实例。

 

关于spring-Aop原理:http://m.oschina.net/blog/174838这篇文章写的很好。

 

 

个人觉着可能上线的时候配置文件更方便一下,所以例子主要是配置文件方式

Demo文件下载地址:

http://download.csdn.net/detail/ruishenh/7261121

 

 

Spring配置文件

/idle-service-impl/src/main/resources/spring/app-config.xml

 

<?xml version="1.0"encoding="UTF-8"?>
<beansxmlns="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"xmlns:context="http://www.springframework.org/schema/context"
         xmlns:util="http://www.springframework.org/schema/util"
         xsi:schemaLocation="
         http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsd
         http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsd
         http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsd
         http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsd
         http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-3.2.xsd">
 
         <context:component-scanbase-package="com.ruishenh.business.impl" />
         <aop:aspectj-autoproxyexpose-proxy="true" proxy-target-class="true"/>
         <context:annotation-config/>
         <!--  -->
         <beanid="springFactoryUtil"class="com.ruishenh.utils.SpringFactoryUtil" />   
         <!--  -->
         <importresource="aop-advisor.xml" />
</beans>
 

 

导入的aop-advisor.xml文件

 

/idle-service-impl/src/main/resources/spring/aop-advisor.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"xmlns:context="http://www.springframework.org/schema/context"
   xmlns:util="http://www.springframework.org/schema/util"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.1.xsd
   http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.1.xsd
   http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd
   http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-3.1.xsd">
 
   <bean id="genericAdvisor" class="com.ruishenh.aop.aspect.advisor.GenericAdvisor"/>
   <aop:config>
      <!-- 定义切面 -->
      <aop:aspect ref="genericAdvisor" order="0">
         <!-- 定义连接点 -->
         <aop:pointcut id="businessService" expression="execution(*com.ruishenh.business.impl..*.*(..))" />
         <!-- 定义前置 -->
         <aop:before method="before" pointcut-ref="businessService"/>
         <!-- 定义环绕 -->
         <aop:around method="heartbeat" pointcut-ref="businessService"/>
         <!-- 定义后置 -->
         <aop:after method="after" pointcut-ref="businessService"/>
         <!-- 定义Target处理后普通结果增强 -->
         <aop:after-returning method="afterReturning" pointcut-ref="businessService" returning="obj"/>
         <!-- 定义Target处理后异常增强 -->
         <aop:after-throwing method="handlerException" pointcut-ref="businessService" throwing="e"/>
        
      </aop:aspect>
   </aop:config>
</beans>

 

 

关于这个类

com.ruishenh.aop.aspect.advisor.GenericAdvisor中方法有

 

1.  before  对应Target执行之前

2.  heartbeat这个是环绕的一个方法

3.  after  对应target执行之后

4.  afterReturning 对应在target处理后结果返回增强处理

5.        handlerException 对应在target执行异常时增强处理

 

 

/idle-service-impl/src/main/java/com/ruishenh/aop/aspect/advisor/GenericAdvisor.java源码

 

package com.ruishenh.aop.aspect.advisor;
 
import org.aspectj.lang.JoinPoint;
importorg.aspectj.lang.ProceedingJoinPoint;
 
import com.ruishenh.domain.account.AccountBank;
 
public class GenericAdvisor {
 
         /**
          * 对于要增强的方法,执行环绕处理检查心跳是否正常
          * @param joinPoint
          * @return
          * @throws Throwable
          */
         Objectheartbeat(ProceedingJoinPoint joinPoint) throws Throwable{
                  
//               if(checkHeartbeat()) {
//                        
//               }
                   System.out.println("2joinPoint.Signature.name:"+joinPoint.getSignature().getName());
                   //记得在调用执行方法的时候异常不要try-catch,要thrwos出去,不然可能事务层没法起效,或者增强异常处理也无法起效
                   Objectobj=joinPoint.proceed();
                   //下边的参入参数可以修改,但是类型和方法的个数要和原来一致,不然原方法无法执行
//               Objectobj=joinPoint.proceed(joinPoint.getArgs());
                  
                   //对于返回后对象,有可能要做处理,对返回参数的某一些值处理,
                   //可以通过org.springframework.beans.BeanUtils.copyProperties把一些值赋值
                   if(obj==null) {
                            returnnew AccountBank();
                   }
                   returnobj;
         }
         /**
          * 对于要增强的方法,在方法之前执行
          * @param joinPoint 连接点信息
          */
         voidbefore(JoinPoint joinPoint){
                   Object[] objs=joinPoint.getArgs();
                   System.out.println("1objs:"+objs[0]);
                   System.out.println("1joinPoint:"+joinPoint);
         };
        
         /**
          * 对于要增强的方法,在方法之后执行
          * @param joinPoint  连接点信息
          */
         voidafter(JoinPoint joinPoint){
                   Object[] objs=joinPoint.getArgs();
                   System.out.println("4objs:"+objs[0]);
                   System.out.println("4joinPoint:"+joinPoint);
         };
         /**
          * 对于要增加的方法,方法返回结果后,对结果进行记录或者分析
          * 方法
          * @param obj target执行后返回的结果
          */
         voidafterReturning(Object obj){
                   System.out.println("3obj:"+obj);
         };
         /**
          * 对于要增强的方法,方法抛出异常后,对异常的增强处理,比如记录异常,或者根据异常分析数据什么的
          * @param e target执行后抛出的异常
          */
         voidhandlerException(Throwable e){
                   System.out.println("handingException......");
                   e.printStackTrace();
         }
        
         booleancheckHeartbeat(){
                   returntrue;
         }
}


 

 

 

 

Junit测试

 

/idle-service-impl/src/test/java/com/ruishenh/business/impl/account/AccountServiceImplTest.java

 

package com.ruishenh.business.impl.account;
 
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
importorg.springframework.test.context.ContextConfiguration;
importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
importcom.ruishenh.domain.account.AccountBank;
importcom.ruishenh.domain.account.AccountBankParam;
import com.ruishenh.utils.SpringFactoryUtil;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/spring/app-config.xml"})
public class AccountServiceImplTest {
 
         @Before
         publicvoid setUp() throws Exception {
         }
 
         @Test
         publicvoid testStoreIn() throws Exception {
                   AccountServiceImplimpl= SpringFactoryUtil.getBean(AccountServiceImpl.class);
                   AccountBankParamparam=   new AccountBankParam();
                   param.setId(100);
                   AccountBankab=impl.storeIn(param);
                   System.out.println(ab.toString());
         }
 
}
 

 

 

执行后输出结果:

 

1objs:com.ruishenh.domain.account.AccountBankParam@d522de2[id=100,name=<null>,account=<null>]

1joinPoint:execution(AccountBankcom.ruishenh.business.impl.account.AccountServiceImpl.storeIn(AccountBankParam))

2joinPoint.Signature.name:storeIn

==============todo=====================

4objs:com.ruishenh.domain.account.AccountBankParam@d522de2[id=100,name=<null>,account=<null>]

4joinPoint:execution(AccountBankcom.ruishenh.business.impl.account.AccountServiceImpl.storeIn(AccountBankParam))

3obj:com.ruishenh.domain.account.AccountBank@2d397e5c[id=0,name=<null>,account=<null>]

com.ruishenh.domain.account.AccountBank@2d397e5c[id=0,name=<null>,account=<null>]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值