网上没找到符合需求的资料,前后鼓捣了两天才弄好。
《Spring in Action》中的aop例子-吟游诗人(Minstrel)虽然生动,但代码不全,可害苦我了:<
后又结合spring reference 6.2节看了半天,才琢麽出来。
需要的jar文件:
spring.jar
commons-logging.jar
aspectjrt.jar
aspectjweaver.jar
cglib-nodep.jar
asm.jar
asm-commons.jar
spring config file: helloworld.xml
<bean id="firsttest" class="firsttest.Firsttest">
<property name="name" value="Atea" />
</bean>
<!--aop bean-->
<bean id="firsttest_AOP" class="firsttest.Firsttest_AOP" />
<aop:config>
<aop:aspect ref="firsttest_AOP">
<!--无参aop-->
<aop:pointcut id="apc1" expression="execution(* aopTest())" />
<aop:before pointcut-ref="apc1" method="whoSayHello" />
<!--带参aop-->
<aop:pointcut id="apc2" expression="execution(* aopTest(firsttest.Firsttest))"/>
<aop:after-returning pointcut-ref="apc2" method="whoSayHello(firsttest.Firsttest)" returning="ft" />
</aop:aspect>
</aop:config>
Firsttest.java
package firsttest;
public class Firsttest {
private String name;
//getter and setter..
public void aopTest(){
System.out.println("aopTest");
}
public Firsttest aopTest(Firsttest ft){
System.out.println("aopTest param");
return ft;
}
}
Firsttest_AOP.java
package firsttest;
public class Firsttest_AOP {
public void whoSayHello(Firsttest ft){
System.out.println(ft.getName() + " said hello!");
}
public void whoSayHello(){
System.out.println("who said hello?");
}
}
MyTest.java
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void hello() {
BeanFactory factory = new ClassPathXmlApplicationContext("helloworld.xml");
Firsttest ft = (Firsttest)factory.getBean("firsttest");
ft.aopTest();
ft.aopTest(ft);
}
}
run result:
who said hello?
aopTest
aopTest param
Atea said hello!