文件结构: package com.macower.spring.aspectj; public class AdviceMethod { public void preExcute(){ System.out.println("------------preExcute------------"); } } package com.macower.spring.aspectj; public class NiveWater { public void testAop(){ System.out.println("----------NiveWater.testAop()------"); } public void testOther(){ System.out.println("----------NiveWater.testOther()------"); } } package com.macower.spring.aspectj; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import junit.framework.TestCase; public class TestAspectJ extends TestCase{ public void testBefore() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("app*.xml"); NiveWater n = (NiveWater)ctx.getBean("niveWater");//测试没指定的类 //pointcut="target(com.macower.spring.aspectj.NiveWater) n.testAop();//测试<aop:aspect>中指定的方法 execution(* testAop(..) n.testOther();//测试<aop:aspect>中没有指定的方法 System.out.println("----------------------------------------"); TNiveWater tn = (TNiveWater)ctx.getBean("tniveWater");//测试没有指定的类 tn.testAop(); } } package com.macower.spring.aspectj; public class TNiveWater { public void testAop(){ System.out.println("----------NiveWater.testAop()------"); } } 配置文件 <?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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <aop:config proxy-target-class="true"> <aop:aspect ref="adviceMethod"><!-- 引用bean --> <!-- target在指定的类上面运用切点,and 表示与 execution 执行指定的表达式的方法,method表示需要在execution中切入的方法 --> <aop:before pointcut="target(com.macower.spring.aspectj.NiveWater) and execution(* testAop(..))" method="preExcute" /> </aop:aspect> </aop:config> <!-- 定义bean --> <bean id="adviceMethod" class="com.macower.spring.aspectj.AdviceMethod" /> <bean id="niveWater" class="com.macower.spring.aspectj.NiveWater" /> <bean id="tniveWater" class="com.macower.spring.aspectj.TNiveWater" /> </beans>