标签:
以下是一个有主函数的简单类:主要作用就是入口
package com.wkj.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class My { public void adds() { System.out.println("add"); } public static void main(String[] args) { ApplicationContext con=new ClassPathXmlApplicationContext("applicationContext.xml"); My my=(My)con.getBean("my"); my.adds(); } }
然后是另外一个Java bean
package com.wkj.aop; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Component @Aspect public class Test { @Pointcut("execution(* com.wkj.aop.*.*(..))") public void add() { } @After(value = "add()") public void after() { System.out.println("after"); } @Before(value = "add()") public void before() { System.out.println("before"); } }
applicationContext.xml是Javabean的配置文件,放在src目录下
<?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:p="http://www.springframework.org/schema/p" 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"> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- 启用AspectJ对Annotation的支持 --> <aop:aspectj-autoproxy /> <bean id="test" class="com.wkj.aop.Test" /> <bean id="my" class="com.wkj.aop.My" /> </beans>
其实这个实现简单到爆,但是jar包找的我头疼。其实用MyEclipse自动添加spring的jar包后,再添加如下图的几个jar包:
spring自动添加的jar包如图:
输出就是我想要的结果:如图
标签:
原文地址:http://my.oschina.net/u/563488/blog/487813