<?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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="log" class="aop.Log" /> <bean id="test1" class="aop.Test"> <constructor-arg value="test1" /> </bean> <bean id="test2" class="aop.Test"> <constructor-arg value="test2" /> </bean> <aop:config> <aop:aspect ref="log"> <aop:pointcut id="aopTest" expression="execution(* aop.Test.go(..)) and bean(test1)"/> <aop:before pointcut-ref="aopTest" method="before" /> </aop:aspect> </aop:config> </beans>
execution(* aop.Test.go(..))
中:*
表示返回類型爲任意,(..)
表示方法參數爲任意;
bean()
接受bean的ID;
and
表示都匹配則匹配。java
package aop; public class Log { public void before(){ System.out.println("before"); } }
package aop; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { private String str; public Test(String str){ this.str = str; } public void go(){ System.out.println(str + " go"); } public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"conf/aop.xml"}); Test test1 = context.getBean("test1", Test.class); Test test2 = context.getBean("test2", Test.class); test1.go(); test2.go(); } }
輸出web
before test1 go test2 go