配置文件代碼: 包括bean context aop三個約束 以及切麵的配置——表達式execution含義、advice通知/增強設置 連接點joinpoint的類,即需要被增強的類: 進行切麵操作的類: 測試的類: 演示效果圖: 瀏覽器無反應 只有Book的方法,沒有前置的before,想來應該 ...
配置文件代碼:
<?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:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 開啟註解掃描 --> <context:component-scan base-package="com.swift"></context:component-scan> <bean id="book" class="com.swift.aop.Book"></bean> <bean id="adviceBook" class="com.swift.aop.AdviceBook"></bean> <aop:config> <!-- 切入點表達式第一個*表示public private等許可權後接空格,第二個*表示任意方法(..)表示參數 --> <aop:pointcut expression="execution(* com.swift.aop.Book.*())" id="pointcut1"/> <!-- 哪個切麵(用來增強切入點的類) 名稱是什麼用ref表示 --> <aop:aspect ref="adviceBook"> <!-- 增強的具體方法,增強哪個切入點 --> <aop:before method="before" pointcut-ref="pointcut1"/> </aop:aspect> </aop:config> </beans>
包括bean context aop三個約束
以及切麵的配置——表達式execution含義、advice通知/增強設置
連接點joinpoint的類,即需要被增強的類:
package com.swift.aop; public class Book { public String fun() { System.out.println("This is Book's fun().............."); return "This is Book's fun().............."; } }
進行切麵操作的類:
package com.swift.aop; public class AdviceBook { public String before() { System.out.println("This is AdviceBook's before()..............."); return "This is AdviceBook's before()..............."; } }
測試的類:
package com.swift.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.swift.aop.Book; @WebServlet("/test") public class ServleTest extends HttpServlet { private static final long serialVersionUID = 1L; public ServleTest() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); ApplicationContext context=new ClassPathXmlApplicationContext("aop.xml"); Book book=(Book)context.getBean("book"); response.getWriter().append(book.fun()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
演示效果圖:
瀏覽器無反應
只有Book的方法,沒有前置的before,想來應該是調用了但是返回的字元串沒能顯示在瀏覽器上
控制台console成功
前置增強在切入點前輸出