遅延Bean初期化による統合テストのパフォーマンスの向上 パーマリンク to "遅延Bean初期化による統合テストのパフォーマンスの向上"

このTipは@atomfredeにより提出されました

多くのSpring Integrationテストでは、すべてのBeanを必要としないため、リポジトリテストなどのコンテキストで すべてのBeanを初期化する必要がなく、貴重な時間を消費します。

src/test/java/YOUR-PACKAGE/configに次の内容のクラス TestLazyBeanInitConfigurationを作成することで、必要なBeanのみが作成されるように、Beanを遅延初期化するようにテストを構成できます。

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Profile("!" + TestLazyBeanInitConfiguration.EAGER_BEAN_INIT)
public class TestLazyBeanInitConfiguration implements BeanFactoryPostProcessor {
    public static final String EAGER_BEAN_INIT = "eager-bean-init";

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Arrays.stream(beanFactory.getBeanDefinitionNames())
            .map(beanFactory::getBeanDefinition)
            .forEach(beanDefinition -> beanDefinition.setLazyInit(true));
    }
}

すべてのBeanを積極的に初期化するテストが必要な場合は、このテストに@ActiveProfiles(TestLazyBeanInitConfiguration.EAGER_BEAN_INIT)というアノテーションを付ける必要があります。

Spring Bootのブログ関連するプルリクエストを参照してください。

実装してくれた@rabioriに感謝します。