`

本人常用的两种spring aop实现方式

阅读更多

备忘一下, 基本的用法包括在配置文件中配置pointcut, 在java中用编写实际的aspect 类, 针对对切入点进行相关的业务处理.

配置文件如下

<?xml version="1.0" encoding="GBK"?>


<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:util="http://www.springframework.org/schema/util"


	xsi:schemaLocation="http://www.springframework.org/schema/beans


         http://www.springframework.org/schema/beans/spring-beans.xsd


         http://www.springframework.org/schema/util 


         http://www.springframework.org/schema/util/spring-util-2.0.xsd


         http://www.springframework.org/schema/aop


         http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"


	default-autowire="byName">





	<!-- aop 拦截器配置 -->


	<aop:aspectj-autoproxy />


          <bean id="cachedDAO" class="com.mysoft.cache.CacheAspect" >


           </bean>


	<aop:config>


       <aop:aspect ref="cachedDAO">


           <aop:around pointcut="execution(* com.mysoft.dao.DAO.getById(long)) and args(Id)" method="getById" arg-names="join,Id"/>


        </aop:aspect>


       </aop:config>


</beans>
 

aspect java类如下:

public class CacheAspect {


	public Object getSpuById(ProceedingJoinPoint join, long spuId) throws Throwable {


		...


	}





}

 所有的就这么简单, 全部搞定, 在需要的地方将该bean配置文件引入即可.

 

第二种方式, 采用注解来做aop, 主要是将写在spring 配置文件中的连接点, 写到注解里面
spring aop配置文件:

	<!-- aop 拦截器配置 -->
	<aop:aspectj-autoproxy />
    <bean id="mockAspect" class="com.taobao.item.mock.aspect.MockAspect" lazy-init="false">
    </bean>

 用来定义连接点和拦截处理的java类:

@Aspect
public class MockAspect {
    @Pointcut("execution(* com.mysoft.manager.propertyManager.*(. .))")
    public void propertyManager() throws Throwable {
    }

    @Pointcut("execution(* com.mysoft.manager.impl.TxtFileManager.*(. .))")
    public void txtFileManager() {
    }

    @Pointcut("execution(* com.mysoft.manager.KeywordsChecker.checkNormalKeywords(. .))")
    public void checkNormalKeywords() {
    }

    @Pointcut("execution(* com.mysoft.manager.KeywordsChecker.checkFixKeywords()) && args(text, ..)")
    public void checkFixKeywords(String text) {
    }

    @Around("propertyManager() || txtFileManager()")
    public Object invoke(ProceedingJoinPoint join) throws Throwable {
        return null;
    }

    @Around("checkNormalKeywords()")
    public String invokeAndReturnString(ProceedingJoinPoint join) throws
            Throwable {
        return "";
    }

    /**
    * @param text
    * @return
    * @throws Throwable
    */
    @Around(value = "checkFixKeywords(text)")
    public String invokeCheckFixKeywords(ProceedingJoinPoint join, String
            text)
            throws Throwable {
        if ("abcflg".equals(text)) {
            return "flg";
        }
        return null;
    }	
 

这里的配置很容易写错, 故我个人还是倾向于在配置文件中写pointcut表达式.

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics