搶先一步
VMware 提供培訓和認證,以加速您的進步。
瞭解更多昨天,Joris 和我在荷蘭 Java 使用者組舉辦了一個會議。我們做了兩次會議,總共有大約 250 人參加了會議。很多人要求提供我們在會議期間所做演示的程式碼。您可以在附件中找到 AOP 和依賴注入演示的程式碼。它展示了一個簡單的切面,在每次 JDBC 操作之前重新整理 Hibernate 會話(不像您在生產程式碼中希望的那樣健壯,但這是一個開始),它還展示了 CarPlant 系統(以前在其他會話中演示過,之前已附加到另一篇部落格文章),該系統使用各種方法配置為在 Spring 2.1 中執行依賴注入(即使用 <bean>、@Bean 和 @Autowired)。
這是一個 Maven2 專案,因此您需要安裝 Maven2。要準備包含所有庫的 Eclipse 專案,請在命令列中 carplant 目錄中執行 mvn eclipse:eclipse。
原始碼:carplant.zip
在會議期間,有人提出了關於一個應用程式上下文中的多個 <aop:config> 塊的問題。觀眾中的那個人不確定兩個或多個 AOP 配置塊是否顯示了預期的結果(建議兩次或多次)。我沒有那個人的電子郵件地址,所以我想在這裡澄清一下。考慮以下程式碼。doIt() 將被建議。實際的建議(為了簡單起見)保留在同一個類中,就像引導 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 里程碑版本。