spring官網學習記錄

  • ApplicationContext實現還允許註冊在容器外部(由用戶)創建的現有對象。這是通過通過方法訪問ApplicationContext的BeanFactory來完成的getBeanFactory(),該方法返回BeanFactory DefaultListableBeanFactory實現。DefaultListableBeanFactory 通過registerSingleton(..)和 registerBeanDefinition(..)方法支持此註冊。但是,典型的應用程序只能與通過常規bean定義元數據定義的bean一起使用。Bean元數據和手動提供的單例實例需要儘早註冊,以便容器在自動裝配和其他自省步驟中正確地推理它們。雖然在某種程度上支持覆蓋現有元數據和現有單例實例,但官方不支持在運行時(與對工廠的實時訪問同時)對新bean的註冊,並且可能導致併發訪問異常,bean容器中的狀態不一致或都。
  • bean實例化

用構造函數實例化 

<bean id="exampleBean" class="examples.ExampleBean"/>
<bean name="anotherExample" class="examples.ExampleBeanTwo"/>

 用靜態工廠方法實例化

<bean id="clientService"
    class="examples.ClientService"
    factory-method="createInstance"/>

public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

    public static ClientService createInstance() {
        return clientService;
    }
}

使用實例工廠方法實例化

<!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</bean>

<!-- the bean to be created via the factory bean -->
<bean id="clientService"
    factory-bean="serviceLocator"
    factory-method="createClientServiceInstance"/>

public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }
}
  • 自定義bean的性質

從Spring 2.5開始,您可以使用三個選項來控制Bean生命週期行爲:

爲同一個bean配置的具有不同初始化方法的多種生命週期機制如下:

  1. 用註釋的方法 @PostConstruct

  2. afterPropertiesSet()InitializingBean回調接口定義

  3. 定製配置的init()方法

銷燬方法的調用順序相同:

  1. 用註釋的方法 @PreDestroy

  2. destroy()DisposableBean回調接口定義

  3. 定製配置的destroy()方法

Aware 接口

名稱 注入依賴

ApplicationContextAware

宣告ApplicationContext

ApplicationEventPublisherAware

附件的事件發佈者ApplicationContext

BeanClassLoaderAware

Class loader used to load the bean classes.

BeanFactoryAware

宣告BeanFactory

BeanNameAware

聲明bean的名稱。

BootstrapContextAware

BootstrapContext容器在其中運行的資源適配器。通常僅在支持JCA的ApplicationContext實例中可用。

LoadTimeWeaverAware

Defined weaver for processing class definition at load time.

MessageSourceAware

解決消息的已配置策略(支持參數化和國際化)。

NotificationPublisherAware

Spring JMX通知發佈者。

ResourceLoaderAware

配置的加載程序,用於對資源的低級別訪問。

ServletConfigAware

當前ServletConfig容器在其中運行。僅在可感知網絡的Spring中有效 ApplicationContext

ServletContextAware

當前ServletContext容器在其中運行。僅在可感知網絡的Spring中有效ApplicationContext

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章