(十二.1)使用xml方式演示AOP

一、核心代码

package target;

//target 目标接口 即核心代码
public interface ArithmeticCalculator {

	int add(int i,int j);
	int div(int i,int j);
}


package target;

import org.springframework.stereotype.Component;

//@Component("arithmeticCalculator")
public class ArithmeticCalculator_impl implements ArithmeticCalculator{

	public int add(int i, int j) {
		// TODO Auto-generated method stub
		return i+j;
	}

	public int div(int i, int j) {
		// TODO Auto-generated method stub
		return i/j;
	}
	

}

二、通知

//通知
public class adviceMethod implements MethodBeforeAdvice/*,AfterReturningAdvice */{

	public void before(Method arg0, Object[] arg1, Object arg2)
			throws Throwable {
		System.out.println("连接点之前执行");
		
	}
/*
	public void afterReturning(Object arg0, Method arg1, Object[] arg2,
			Object arg3) throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("连接点之后执行");
	}
	*/

}

三、applicationContext.xml

<!-- target -->
 <bean id="arithmeticCalculator_impl" class="target.ArithmeticCalculator_impl">
       
 </bean>

<!-- advice -->
 <bean id="hijackBeforeMethodBean" class="advice.adviceMethod">
       
 </bean>

<!-- 切点 -->
<bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- target:定义想要拦截的bean -->
   <property name="target" ref="arithmeticCalculator_impl" />
   
<!-- interceptorNames:定义要应用代理/目标对象的类 -->
   <property name="interceptorNames"> 
      <list>
         <value>hijackBeforeMethodBean</value>
      </list>
   </property>
</bean>


</beans>

四、Test

package soundsystem;

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

import target.ArithmeticCalculator;
import target.ArithmeticCalculator_impl;



public class Test {

	public static void main(String[] args) {
		ApplicationContext context = 
	             new ClassPathXmlApplicationContext("applicationContext.xml");
		ArithmeticCalculator im=(ArithmeticCalculator)context.getBean("customerServiceProxy");
	    
	   System.out.println(im.add(1, 2));
	   
	    
	}
}

遇到问题:

Spring Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator

原因:缺少aspectjweare包:https://mvnrepository.com/artifact/org.aspectj/aspectjweaver/1.9.1(下载)

②ClassCastException:com.sun.proxy.$Proxy2 cannot be cast

原因:target类有要实现接口,不用具体的类,用接口即可。

posted @ 2019-05-14 19:31  测试开发分享站  阅读(102)  评论(0编辑  收藏  举报