2007 年 6 月 13 日 NL-JUG 會議中展示的 Demo 程式碼

工程 | Alef Arendsen | 2007 年 6 月 14 日 | ...

昨天,Joris 和我參加了荷蘭 Java 使用者群組的會議。我們進行了兩次會議,總共有大約 250 人參加了會議。很多人詢問我們在會議中展示的 Demo 程式碼。您可以在附件中找到 AOP 和 Dependency Injection 的 Demo 程式碼。它展示了一個簡單的 Aspect,在每個 JDBC 操作之前刷新 Hibernate Session (並不像您希望在生產環境中那樣強大,但這是一個開始),它還展示了 CarPlant 系統 (之前在其他會議中展示過,並且之前附加到另一個部落格文章),該系統使用各種方式在 Spring 2.1 中執行 Dependency Injection (即使用 <bean>、@Bean 和 @Autowired)。

這是一個 Maven2 專案,因此您需要安裝 Maven2。若要準備包含所有程式庫的 Eclipse 專案,請在 carplant 目錄中的命令列執行 mvn eclipse:eclipse。

原始碼:carplant.zip

在會議期間,有人提出了關於在一個應用程式上下文中有多個 <aop:config> 區塊的問題。這位聽眾不確定兩個或多個 AOP 組態區塊是否顯示預期的結果(建議兩次或更多次)。我沒有這位聽眾的電子郵件地址,所以我想在這裡澄清一下。考慮以下程式碼。doIt() 將被建議。為了簡單起見,實際的 Advice 保留在同一個類別中,就像啟動 ApplicationContext 的 main 方法一樣。


public class Logger {

  public void doIt() {

  }

  public void log() {
    System.out.println("Log!");
  }

  public static void main(String args[]) {
    ApplicationContext context = 
      new ClassPathXmlApplicationContext(
        new String[] {"com/carplant/context1.xml", "com/carplant/context2.xml"});

    Logger logger = (Logger)context.getBean("logger");

    logger.doIt();
  }
}

組態 1:一個簡單的 AOP 組態區塊

在這種情況下,context2.xml 是空的,而 context1.xml 包含以下程式碼

<bean id="logger" class="Logger"/>

<aop:config>
	<aop:pointcut id="doItOperation" expression="execution(* doIt(..))"/>
	<aop:aspect ref="logger">
		<aop:before pointcut-ref="doItOperation" method="log"/>
	</aop:aspect>
</aop:config>

正如預期的那樣,在呼叫 doIt() 方法時,我們只會從記錄器中獲得一行輸出(它只被建議一次)。

組態 2:兩個 AOP 組態區塊在兩個不同的檔案中

context2.xml 現在與 context1.xml(在上面的範例中)相同,唯一的區別是在 context2.xml 中我們沒有名為 logger 的 bean。當執行此情境時,我們將看到兩個 Log! 輸出條目。doIt() 方法被建議兩次。

組態 3:兩個 AOP 組態區塊在同一個組態檔案中

context2.xml 再次為空。另一方面,context1.xml 現在包含兩個 <aop:config> 區塊。兩者之間唯一的區別是切入點識別符號(這是一個 XML ID,因此在 XML 檔案中應該是唯一的)。

<bean id="logger" class="Logger"/>

<aop:config>
	<aop:pointcut id="doItOperation" expression="execution(* doIt(..))"/>
	<aop:aspect ref="logger">
		<aop:before pointcut-ref="doItOperation" method="log"/>
	</aop:aspect>
</aop:config>

<aop:config>
	<aop:pointcut id="doItOperation2" expression="execution(* doIt(..))"/>
	<aop:aspect ref="logger">
		<aop:before pointcut-ref="doItOperation2" method="log"/>
	</aop:aspect>
</aop:config>

執行此操作也會顯示 bean 將被建議兩次。

請注意,我正在這裡使用 2.1 里程碑版本。

取得 Spring 電子報

隨時掌握 Spring 電子報的最新資訊

訂閱

搶先一步

VMware 提供培訓和認證,以加速您的進展。

了解更多

獲得支援

Tanzu Spring 在一個簡單的訂閱中提供 OpenJDK™、Spring 和 Apache Tomcat® 的支援和二進位檔案。

了解更多

即將舉行的活動

查看 Spring 社群中所有即將舉行的活動。

查看全部