かんがるーさんの日記

最近自分が興味をもったものを調べた時の手順等を書いています。今は Spring Boot をいじっています。

Singleton のクラスを遅延生成させるには

Spring Boot でログイン画面 + 一覧画面 + 登録画面の Webアプリケーションを作る ( その24 )( 登録画面のドロップダウンリストを設定ファイルから取得する方法の変更 ) の考察で、「起動時ではなく最初にアクセスされた時に生成してくれるオプションがあるといいのですが、そういうものはないのでしょうか?」と書きましたが、その方法を見つけました。

Spring Framework のマニュアルの以下のページに記述がありました。

Spring Framework Reference Documentation - 5.4.4 Lazy-initialized beans
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-lazy-init

 
特定クラスを遅延生成させたい場合には、クラスに @Lazy アノテーションを付加します。

@Controller
@Lazy
public class LoginController {

 
全てのクラスを遅延生成させたい場合には BeanFactoryPostProcessor インターフェースを実装した Java Configuration のクラスを作成して、その中で setLazyInit(true) を呼び出します。

package ksbysample.webapp.basic.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanFactoryConfig implements BeanFactoryPostProcessor {

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            beanFactory.getBeanDefinition(beanName).setLazyInit(true);
        }
    }

}

 
ただし作成中の ksbysample-webapp-basic で試してみましたが、速くはなりませんでした。クラス数も全然ありませんからね。。。 何かで使うこともあるかもしれないので、メモ書きとして残しておきます。