引用一个猴子偷桃,守护者守护果园抓住猴子的小情节。
1、猴子偷桃类(普通类):
- package com.samter.aspect;
- import org.aspectj.lang.annotation.AfterReturning;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Before;
- import org.aspectj.lang.annotation.Pointcut;
- /**
- * 桃园守护者
- * @author Administrator
- *
- */
- @Aspect
- public class Guardian {
- @Pointcut("execution(* com.samter.common.Monkey.stealPeaches(..))")
- public void foundMonkey(){}
- @Before(value="foundMonkey()")
- public void foundBefore(){
- System.out.println("【守护者】发现猴子正在进入果园...");
- }
- @AfterReturning("foundMonkey() && args(name,..)")
- public void foundAfter(String name){
- System.out.println("【守护者】抓住了猴子,守护者审问出了猴子的名字叫“"+name+"”...");
- }
- }
- <?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-2.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
- >
- <!-- 定义Aspect -->
- <bean id="guardian" class="com.samter.aspect.Guardian" />
- <!-- 定义Common -->
- <bean id="monkey" class="com.samter.common.Monkey" />
- <!-- 启动AspectJ支持 -->
- <aop:aspectj-autoproxy />
- </beans>
- package com.samter.common;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class Main {
- public static void main(String[] args) {
- ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
- Monkey monkey = (Monkey) context.getBean("monkey");
- try {
- monkey.stealPeaches("孙大圣的大徒弟");
- }
- catch(Exception e) {}
- }
- }