需要添加方法的类:
package com.xh.spring.aop;
public class CutPoint {
public void doSomething()
{
System.out.println("I am donging something:");
}
}
提供方法的类:
package com.xh.spring.aop;
public class TestAspect {
public void doBefore()
{
System.out.println("I do it before");
}
public void doAfter()
{
System.out.println("I do it After");
}
}
测试类:
package com.xh.spring.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xh.spring.aop.CutPoint;
public class CutPointTest {
@Test
public void test() {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
CutPoint cut=(CutPoint) app.getBean("B_cut");
cut.doSomething();
}
}
xml:
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <bean id="B_cut" class="com.xh.spring.aop.CutPoint"></bean> <bean id="B_asp" class="com.xh.spring.aop.TestAspect"></bean> <aop:config> <aop:aspect id="myAop" ref="B_asp"> <aop:pointcut expression=" execution(* com.xh.spring.aop.CutPoint.doSomething(..))" id="cut" /> <aop:before pointcut-ref="cut" method="doBefore"/> <aop:after pointcut-ref="cut" method="doAfter"/> </aop:aspect> </aop:config> </beans>