Spring AOP使用整理:自动代理及AOP命名空间

三、自动代理的实现

     1、使用BeanNameAutoProxyCreator

          通过Bean的name属性自动生成代理Bean。

<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
	<property name="beanNames">
		<list>
			<value>*Target</value> <!-- 名字以Target结尾的bean将被拦截 -->
		</list>
	</property>
	<property name="interceptorNames">
		<list>
			<value>personAroundAdvice</value>
		</list>
	</property>
 </bean>

 

     2、使用DefaultAdvisorAutoProxyCreator

          DefaultAdvisorAutoProxyCreator允许我们只需定义相应的Advisor通知者,就可以完成自动代理。配置好DefaultAdvisorAutoProxyCreator受管Bean后,它会自动查找配置文件中定义的Advisor,并将它们作用于所有的Bean。

          Spring提供了以下通知者:

                RegexpMethodPointcutAdvisor
                NameMatchMethodPointcutAdvisor

<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>

<bean id="nameMatchMethodPointcutAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
	<property name="advice" ref="personAroundAdvice"/>
	<property name="mappedNames">
		<list>
			<value>*info*</value>
		</list>
	</property>
</bean>

 

      3、测试代码

ApplicationContext context = new FileSystemXmlApplicationContext("classpath:com/cjm/aop/beans.xml");
Person p = (Person)context.getBean("personTarget");  //此处获取的是具体的Bean,而不是代理Bean
p.info();

 

四、基于aop命名空间的AOP

     1、切面类MyAspect的源码

public class MyAspect {
	public void BeforeAdvice(JoinPoint point){
		PersonImpl p = (PersonImpl)point.getTarget();
	}
	
	public void AfterAdvice(JoinPoint point){
		PersonImpl p = (PersonImpl)point.getTarget();
	}
	
	public void AfterReturningAdvice(Object retValue){
		System.out.println(retValue);
	}
	
	public void AroundAdvice(ProceedingJoinPoint point)throws Throwable{
		System.out.println("AroundAdvice >> 目标对象 前");
		point.proceed(point.getArgs());
		System.out.println("AroundAdvice >> 目标对象 后");
	}
	
	public void ThrowingAdvice(Throwable throwing)throws Throwable{
		System.out.println(throwing);
	}
}

 

     2、配置

<!-- 切面受管Bean -->
<bean id="myAspect" class="com.cjm.aop.MyAspect"/>

<aop:config proxy-target-class="true">
	<!-- 声明一个切面 -->
	<aop:aspect ref="myAspect" order="0">
		<!-- 声明一个切入点 -->
		<aop:pointcut id="pointcut1" expression="execution(* com.cjm.aop..*(..))"/>
		
		<!-- 声明通知 -->
		<aop:before pointcut-ref="pointcut1" method="BeforeAdvice"/>
		<aop:after pointcut-ref="pointcut1" method="AfterAdvice"/>
		<aop:after-returning pointcut-ref="pointcut1" method="AfterReturningAdvice" returning="retValue"/>
		<aop:around pointcut-ref="pointcut1" method="AroundAdvice"/>
		<aop:after-throwing pointcut-ref="pointcut1" method="ThrowingAdvice" throwing="throwing"/>
	</aop:aspect>
</aop:config>

 

你可能感兴趣的:(spring,AOP,bean,xml)