Spring AOP小例子
PS: 要注明一下,这个是转载滴
这里给一个完整的例子,以帮助初学者更好地理解,
你们可以先不必理会上面的概念,等运行这个例子后,再慢慢地做照着理解。
我使用的是Spring 2.0 的AOP, 它引入了一种更加简单并且更强大的方式来定义切面。
马上开始吧:
首先建一个普通Java项目:com.longthsoft.learn.spring
把 spring.jar, commons-logging.jar, cglib-nodep-...jar, aspectjweaver.jar, aspectjrt.jar 放到 Build Path 下.
以止 lib 除了 spring 外, 其他的都可以在 spring 下载包的 lib 中找到
下面编码开始:
让我们先写两个简单的类:
package com.longthsoft.learn.spring.models; public class A { public void sayHello() { System.out.println("Hello, I'm a"); } }
package com.longthsoft.learn.spring.models; public class B { public void sayHi() { System.out.println("Hi, I'm b"); } }
<?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"> <bean id="a" /> <bean id="b" /> </beans>
package com.longthsoft.learn.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.longthsoft.learn.spring.models.A; import com.longthsoft.learn.spring.models.B; public final class Boot { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); A a = (A) ctx.getBean("a"); a.sayHello(); B b = (B) ctx.getBean("b"); b.sayHi(); } }
package com.longthsoft.learn.spring; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; @Aspect public class SimpleAspect { @Pointcut("execution(* com.longthsoft.learn.spring.models.*.say*())") public void simplePointcut() { } @AfterReturning(pointcut="simplePointcut()") public void simpleAdvice() { System.out.println("Merry Christmas"); } }
<?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"> <aop:aspectj-autoproxy /> <bean id="a" /> <bean id="b" /> <bean id="simpleAspect" /> </beans>