[除了使用XML配置外,還可以選擇使用基于注解(annotation)的配置方式,其依賴于字節碼來織入組件。注解注入在XML注入之前完成,因此在XML配置中可以重載注解注入的屬性。
一、建一個SpringUtil類
package com.ceopen.eoss.spring; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext context) throws BeansException { SpringUtil.applicationContext = context; } public static Object getBean(String name){ return applicationContext.getBean(name); } }
將SpringUtil注入spring配置文件[Spring IoC容器中Bean的作用范圍詳解 作用域將對Bean的生命周期和創建方式產生影響. singleton? 在spring IOC容器中僅存在一個Bean實例,Bean以單實例的方式存在. ]
二、如下取得注入Spring 中的對象
ICBMission icbMission = (ICBMission)SpringUtil.getBean("ICBMission");[在上一小節中,演示了如何使用代碼層次上的注解來配置元數據。但是,大量的基礎bean還是顯式的定義在XML文件中,注解只是用來完成依賴注入。該小節提供了一種選擇,通過掃