Spring架構中的aop操作之二 通過設定檔實現增強,springaop
設定檔代碼:
<?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成功
前置增強在切入點前輸出