源码分析
java">
public final class LazyInitializationBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {Collection<LazyInitializationExcludeFilter> filters = beanFactory.getBeansOfType(LazyInitializationExcludeFilter.class, false, false).values();for (String beanName : beanFactory.getBeanDefinitionNames()) {BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);if (beanDefinition instanceof AbstractBeanDefinition) {postProcess(beanFactory, filters, beanName, (AbstractBeanDefinition) beanDefinition);}}}private void postProcess(ConfigurableListableBeanFactory beanFactory,Collection<LazyInitializationExcludeFilter> filters, String beanName,AbstractBeanDefinition beanDefinition) {Boolean lazyInit = beanDefinition.getLazyInit();if (lazyInit != null) {return;}Class<?> beanType = getBeanType(beanFactory, beanName);if (!isExcluded(filters, beanName, beanDefinition, beanType)) {beanDefinition.setLazyInit(true);}}private Class<?> getBeanType(ConfigurableListableBeanFactory beanFactory, String beanName) {try {return beanFactory.getType(beanName, false);}catch (NoSuchBeanDefinitionException ex) {return null;}}private boolean isExcluded(Collection<LazyInitializationExcludeFilter> filters, String beanName,AbstractBeanDefinition beanDefinition, Class<?> beanType) {if (beanType != null) {for (LazyInitializationExcludeFilter filter : filters) {if (filter.isExcluded(beanName, beanDefinition, beanType)) {return true;}}}return false;}@Overridepublic int getOrder() {return Ordered.HIGHEST_PRECEDENCE;}}
测试案例
java">class LazyInitializationExcludeFilterTests {@Testvoid forBeanTypesMatchesTypes() {LazyInitializationExcludeFilter filter = LazyInitializationExcludeFilter.forBeanTypes(CharSequence.class,Number.class);String beanName = "test";BeanDefinition beanDefinition = mock(BeanDefinition.class);System.out.println("验证filter是否正确排除了CharSequence类型:"+filter.isExcluded(beanName, beanDefinition, CharSequence.class));System.out.println("验证filter是否正确排除了String类型(CharSequence的子类型):"+filter.isExcluded(beanName, beanDefinition, String.class));System.out.println("验证filter是否正确排除了StringBuilder类型(CharSequence的子类型):"+filter.isExcluded(beanName, beanDefinition, StringBuilder.class));System.out.println("验证filter是否正确排除了Number类型:"+filter.isExcluded(beanName, beanDefinition, Number.class));System.out.println("验证filter是否正确排除了Long类型(Number的子类型):"+filter.isExcluded(beanName, beanDefinition, Long.class));System.out.println("验证filter是否正确不排除Boolean类型(非Number类型):"+filter.isExcluded(beanName, beanDefinition, Boolean.class));}}
测试结果
验证filter是否正确排除了CharSequence类型:true
验证filter是否正确排除了String类型(CharSequence的子类型):true
验证filter是否正确排除了StringBuilder类型(CharSequence的子类型):true
验证filter是否正确排除了Number类型:true
验证filter是否正确排除了Long类型(Number的子类型):true
验证filter是否正确不排除Boolean类型(非Number类型):false