代码:
package com.qhong; import org.aspectj.lang.ProceedingJoinPoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml"); Person babyPerson=(BabyPerson)context.getBean("babyPerson"); babyPerson.eatBreakfast(); babyPerson.eatLunch(); babyPerson.eatSupper(); } } interface Person { public void eatBreakfast(); public void eatLunch(); public void eatSupper(); } class BabyPerson implements Person{ @Override public void eatBreakfast() { System.out.println("小Baby正在吃早餐"); } @Override public void eatLunch() { System.out.println("小Baby正在吃午餐"); } @Override public void eatSupper() { System.out.println("小Baby正在吃晚餐"); } } class AdviceMethod { public void beforeEat(){ System.out.println("-------------------吃饭之前先洗小手!--------------------"); } public void afterEat(){ System.out.println("-------------------午饭吃完要睡午觉!--------------------"); } public Object aroundEat(ProceedingJoinPoint pjp) throws Throwable{ System.out.println("-------------------吃晚饭前先玩一玩!-------------------"); Object retVal = pjp.proceed(); System.out.println("-------------------晚饭吃完后要得睡觉了!-------------------"); return retVal; } }
beans.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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean id="babyPerson" class="com.qhong.BabyPerson"/><!-- 被增强的bean --> <bean id="adviceAspect" class="com.qhong.AdviceMethod"/><!-- 增强方法的bean --> <aop:config proxy-target-class="true"> <!-- 定义切点 --> <aop:pointcut id="pointcut" expression="execution(* com.qhong.BabyPerson.*(..))"/> <!-- 定义切面 --> <aop:aspect ref="adviceAspect"> <!-- 定义前置增强方法 --> <aop:before method="beforeEat" pointcut-ref="pointcut" /> <!--定义后置增加,使用匿名切点 --> <aop:after method="afterEat" pointcut="execution(* com.qhong.BabyPerson.eatLunch(..))"/> <!--定义后置增加,使用匿名切点 --> <aop:around method="aroundEat" pointcut="execution(* com.qhong.BabyPerson.eatSupper(..))"/> </aop:aspect> </aop:config> </beans>
http://www.kancloud.cn/evankaka/springlearning/119669
原文:http://www.cnblogs.com/hongdada/p/6512400.html