ビーンの性質をカスタマイズする
ライフサイクルインターフェース
SpringではBeanFactory中でビーンの振る舞いを変更するためのマーカーインタフェースがいくつか
提供されています。
InitializingBeanインタフェース
org.springframework.beans.factory.InitializingBeanを実装すると、BeanFactoryが必要な
プロパティを全て設定した後にビーンに初期化を実行させることができるようになる。
* Invoked by a BeanFactory after it has set all bean properties supplied * (and satisfied BeanFactoryAware and ApplicationContextAware). * <p>This method allows the bean instance to perform initialization only * possible when all bean properties have been set and to throw an * exception in the event of misconfiguration. * @throws Exception in the event of misconfiguration (such * as failure to set an essential property) or if initialization fails. */ void afterPropertiesSet() throws Exception;
DisposableBeanインタフェース
org.springframework.beans.factory.DisposableBeanインタフェースを実装すると、そのビーンが含まれているBeanFactoryがデストロイされたときにビーンがコールバックを受け取ることができるようになります。
/** * Invoked by a BeanFactory on destruction of a singleton. * @throws Exception in case of shutdown errors. * Exceptions will get logged but not rethrown to allow * other beans to release their resources too. */ void destroy() throws Exception;
BeanFactoryAwareインタフェース
org.springframework.beans.factory.BeanFactoryAwareインタフェースを実装したクラスはそれを
生成したBeanFactoryへのリファレンスをもっており、それはBeanFactoryによって生成されたときに渡されます。
public interface BeanFactoryAware { /** * Callback that supplies the owning factory to a bean instance. * <p>Invoked after population of normal bean properties but before an init * callback like InitializingBean's afterPropertiesSet or a custom init-method. * @param beanFactory owning BeanFactory (may not be null). * The bean can immediately call methods on the factory. * @throws BeansException in case of initialization errors * @see BeanInitializationException */ void setBeanFactory(BeanFactory beanFactory) throws BeansException; }
BeanNameAwareインタフェース
org.springframework.beans.factory.BeanNameAwareインタフェースを実装するビーンがあって、
それが、BeanFactory中にデプロイされている場合、そのBeanFactoryはそのビーンをこのインタフェース
経由で呼び出し、デプロイ下にいるという印にそのビーンのIDを設定する。このコールバックは、
InitializingBeanのafterPropertiesSetもしくは独自のinit-methodのように通常のビーンプロパティ
が構成された後、コールバックが初期化される前に起動される。
void setBeanName(String):ビーンに名前が何かを知らしめるために呼ばれるメソッド
ApplicationContextを導入する
ApplicationContextが含まれているcontextパッケージですが,これはbeansパッケージの上位に位置付け
られているパッケージです。
ApplicationContextを利用する場合、BeanFactoryのようにユーザが手動で生成してあげる必要がないらしいです。
というのは、J2EEのWebアプリの場合に、起動手順の一部としてApplicationContextをContextLoaderのようなサポートクラスに依存させて生成するというようなアプローチができるらしい。
むずかしいことはよくわからないけど、BeanFactoryの機能に加えて以下のような機能が拡張されています。
- 国際化対応のメッセージにアクセスできます.
- URLやファイルなどのリソースにアクセスできます.
- イベントを伝播してくれます.
- 複数のコンテキストをロードできます*1.