領先一步
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的主方法一樣。
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的里程碑版本。