一、實現類介紹java
package com.yyq.aop; public class Waiter { public void greetTo(String name) { System.out.println("waiter greet to " + name + "."); } public void serveTo(String name) { System.out.println("waiter serving to " + name + "."); } }
Seller業務類:spring
package com.yyq.aop; public class Seller { public void greetTo(String name) { System.out.println("seller greet to " + name + "."); } }
GreetingBeforeAdvice前置加強實現類:ide
package com.yyq.aop; import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; public class GreetingBeforeAdvice implements MethodBeforeAdvice { @Override public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println(o.getClass().getName() + "." + method.getName()); String clientName = (String) objects[0]; System.out.println("Hi! Mr." + clientName + "."); } }
使用Bean名進行自動代理配置:測試
<bean id="waiterTarget" class="com.yyq.aop.Waiter"/> <bean id="sellerTarget" class="com.yyq.aop.Seller"/> <bean id="greetingAdvice" class="com.yyq.aop.GreetingBeforeAdvice"/> <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator" p:beanNames="*Target" p:interceptorNames="greetingAdvice" p:optimize="true"/>
@Test public void testAdvisor6(){ String configPath = "com\\yyq\\aop\\beans.xml"; ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath); Waiter waiter = (Waiter)ctx.getBean("waiterTarget"); Seller seller = (Seller)ctx.getBean("sellerTarget"); waiter.greetTo("Peter"); seller.greetTo("Tom"); }
輸出結果:spa
<bean id="waiterTarget" class="com.yyq.aop.Waiter"/> <bean id="sellerTarget" class="com.yyq.aop.Seller"/> <bean id="greetingAdvice" class="com.yyq.aop.GreetingBeforeAdvice"/> <bean id="regexpAdvisor2" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor" p:pattern=".*greet.*" p:advice-ref="greetingAdvice"/> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
測試方法:代理
@Test public void testAdvisor7(){ String configPath = "com\\yyq\\aop\\beans.xml"; ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath); Waiter waiter = (Waiter)ctx.getBean("waiterTarget"); Seller seller = (Seller)ctx.getBean("sellerTarget"); waiter.greetTo("Peter"); waiter.serveTo("Peter"); seller.greetTo("Tom"); }