読者です 読者をやめる 読者になる 読者になる

liguofeng29’s blog

個人勉強用ブログだっす。

Spring4 - BeanFactoryPostProcessor

Beanを遅延生成させる

@Component
public class LazyInitBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            // bean名がcomponentB以外は遅延生成に設定
            if (!"componentB".equals(beanName)) {
                beanFactory.getBeanDefinition(beanName).setLazyInit(true);
            }
        }
    }
}

git:
https://github.com/liguofeng29/java-project/tree/master/src/main/java/spring4/third/lazyInitSample

Beanのscopeを変更する

package spring4.third.modifyBeanDefine;

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

@Component
public class ModifyBeanDefinitionFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            // componentBのscopeを変更する
            if (beanName.equals("componentB")) {
                beanFactory.getBeanDefinition(beanName).setScope("prototype");
            }
        }
    }
}

git:
https://github.com/liguofeng29/java-project/tree/master/src/main/java/spring4/third/modifyBeanDefine