一、要增加強的類java
package com.test.springadvicetype; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; /** * 服務員類 */ @Component public class Waiter { /** * 服務 * @param name */ public String serve(String name) { System.out.println(name + ",您好,很高興爲您服務。"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); return name + ",您好,如今是北京時間" + format.format(new Date()); } /** * 開車 * @param name */ public void driving(String name) { throw new RuntimeException(name + ",您好,禁止酒後駕車!"); } }
二、環繞加強,實現 MethodInterceptor 接口spring
package com.test.springadvicetype.methodinterceptor; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.stereotype.Service; /** * 環繞加強 */ @Service public class SpringMethodInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { // 前置加強 System.out.println("前置加強執行了"); // 經過反射機制調用目標方法 Object obj = invocation.proceed(); // 後置加強 System.out.println("後置加強執行了"); return obj; } }
三、xml,spring-chapter3-springaoptype.xmlide
<?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" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 開啓註解掃描 --> <context:component-scan base-package="com.test.springadvicetype"/> </beans>
四、運行測試代碼測試
package com.test.springadvicetype.methodinterceptor; import com.test.springadvicetype.Waiter; import org.springframework.aop.framework.ProxyFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Spring環繞加強測試 */ public class SpringMethodInterceptorDemo { public static void main(String[] args) { System.out.println("Spring環繞加強測試"); System.out.println("==========我是分割線=========="); ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-chapter3-springaoptype.xml"); Waiter waiter = (Waiter) context.getBean("waiter"); SpringMethodInterceptor advice = (SpringMethodInterceptor) context.getBean("springMethodInterceptor"); //Spring提供的代理工廠 ProxyFactory pf = new ProxyFactory(); //設置代理目標 pf.setTarget(waiter); pf.addAdvice(advice); //生成代理實例 Waiter proxy = (Waiter)pf.getProxy(); proxy.serve("Michael"); System.out.println("==========我是分割線=========="); proxy.serve("Tommy"); } }
五、運行結果spa
Spring環繞加強測試 ==========我是分割線========== 前置加強執行了 Michael,您好,很高興爲您服務。 後置加強執行了 ==========我是分割線========== 前置加強執行了 Tommy,您好,很高興爲您服務。 後置加強執行了