Spring 中面向AOP之一系列做法

时间:2023-03-09 21:59:10
Spring 中面向AOP之一系列做法

Spring的AOP实现是通过集成AspectJ框架实现的。

想必这句话大家都知道了吧,不知道也没关系,最起码你现在知道了。

四种实现方案,接下来我们一一去揭开它的神秘的面纱.......

第一种(伪代码的形式)

经典AOP形式的:

<bean id="userDao" class="UserDaoImpl"></bean>

<bean id="service" class="UserServiceImpl">

<property name="dao" ref="userDao"></property>

</bean>

<bean id="myBefore" class="MyBeforeAdvice"></bean>

<bean id="myAfter" class="MyAfterAdvice"></bean>

<aop:config>

<aop:pointcut id="point" expression="execution(* *..biz.*.*(..))"></aop:pointcut>

<aop:advisor pointcut-ref="point" advice-ref="myBefore"></aop:advisor>

<aop:advisor pointcut-ref="point" advice-ref="myAfter"></aop:advisor>

</aop:config>

第二种(伪代码形式)

使用注解方式

@Aspect

public class MyBeforeAspect{

@Before(value="execution(* *..biz.*.*(..))")

public void before(){

System.out.println("====before===");

}

@AfterReturning(value="execution(* *..biz.*.*(..))")

public void after(){

System.out.println("=====after=====");

}

}

<bean id="stuDao" class="StudentDaoImpl"></bean>

<bean id="stuService" class="StudentService">

<property name="dao" ref="stuDao">

</bean>

<!-- 准备aop:aspectj-autoproxy-->

<bean class="MyBeforeAspect"></bean>

<aop:aspectj-autoproxy />

第三种(伪代码形式)

使用AspectJ基于xml形式

public class MyAspectJMethod{

public void myBefore(){

System.out.println("AspectJ=========before");

}

public void myAfter(){

System.out.println("AspectJ==========after");

}

}

<bean id="stuDao" class="StudentDaoImpl"></bean>

<bean id="stuBiz" class="StudentBizImpl"></bean>

<bean id="myAspectJ" class="MyAspectJMethod">

<aop:config>

<aop:pointcut id="point" expression="execution(* *..biz.*.*(..))"></aop:pointcut>

<aop:aspect ref="myAspectJ">

<aop:before method="myBefore" ponitcut-ref="point"></aop:before>

<aop:after method="myAfter" pointcut-ref="point"></aop:after>

</aop:aspect>

</aop:config>

上面配置<aop:pointcut>节点也可以放到<aop:aspect>节点内,如下:

<aop:config>

<aop:aspect ref="myAspectJ">

<aop:pointcut id="point" expression="execution(* *..biz.*.*(..))"></aop:pointcut>

<aop:before method="myBefore" ponitcut-ref="point"></aop:before>

<aop:after method="myAfter" pointcut-ref="point"></aop:after>

</aop:aspect>

</aop:config>

上述两种配置都可以实现该功能。。。。。