配置文件:
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="aService" class="com.aop.services.Aservice"></bean> <bean id="bService" class="com.aop.services.Bservice"></bean> <!--切面类--> <bean id="myAspect" class="com.aop.aspects.MyAspect"></bean> <aop:config> <!--切面类配置 --> <aop:aspect ref="myAspect" id="my"> <!-- 切入点配置 --> <aop:pointcut expression="execution(* com.aop.services.*.*(..))" id="mytarget" /> <!--通知方式 --> <aop:after method="doAfter" pointcut-ref="mytarget" /> <aop:before method="doBefore" pointcut-ref="mytarget" /> </aop:aspect> </aop:config> </beans>
切面类:
public class MyAspect { public void doAfter(JoinPoint jp) { System.out.println("调用后"+jp.getTarget().getClass().getName() + "." + jp.getSignature().getName()); } public void doBefore(JoinPoint jp) { System.out.println("调用前"+jp.getTarget().getClass().getName() + "调用方法." + jp.getSignature().getName()); } }
普通业务类
public interface IService { public void foo(String msg ,int type); public void bar(); } public class Aservice implements IService { public void bar() { // TODO Auto-generated method stub } public void foo(String msg, int type) { // TODO Auto-generated method stub System.out.println("AServiceImpl.barA(msg:"+msg+" type:"+type+")"); } } public class Bservice implements IService { public void bar() { // TODO Auto-generated method stub System.out.println("BServiceImpl.fooB()"); } public void foo(String msg, int type) { // TODO Auto-generated method stub System.out.println("BServiceImpl.barB(msg:"+msg+" type:"+type+")"); } }
测试类:
public class TestAop { /** * @param args */ @SuppressWarnings("deprecation") public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ac = new FileSystemXmlApplicationContext( "src/applicationContext.xml"); IService aService = (IService) ac.getBean("aService"); IService bService = (IService) ac.getBean("bService"); System.out.println("开始调用aService方法"); aService.foo("hello", 0); System.out.println("--------------------"); System.out.println("开始调用bService方法"); bService.foo("world", 1); } }