搶先一步
VMware 提供培訓和認證,以加速您的進展。
了解更多昨天,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();
}
}
<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() 方法時,我們只會從記錄器中獲得一行輸出(它只被建議一次)。
<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 里程碑版本。