Spring Bean 生命周期内的 Exception 复现

2021-02-04

涉及 Bean 相关的异常说明:

  • NoSuchBeanDefinitionException:Bean 不存在
  • NoUniqueBeanDefinitionException:多个 Bean
  • BeanInstantiationException:注册了无法实例化的 Bean
  • BeanCreationException:Bean 的初始化过程报错,如 init 方法内报错
  • BeanDefinitionStoreException:BeanFactory 遇到非法的 BeanDefinition,如 xml 路径不对

 

复现代码:

spring xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
    <bean name="user1" class="constxiong.User"/>
    <bean name="user2" class="constxiong.User"/>
</beans>

 

测试代码

/**
 * 测试 Bean 生命周期内的异常
 * @author ConstXiong
 */
@Configuration
public class Test {
	
	public static void main(String[] args) throws InterruptedException {
		ApplicationContext context = new ClassPathXmlApplicationContext("/META-INF/spring-bean-exception.xml");
		//NoSuchBeanDefinitionException,Bean 不存在
		exec(() -> context.getBean("user"));
		Thread.sleep(100L);

		//NoUniqueBeanDefinitionException,多个 Bean
		exec(() -> context.getBean(User.class));
		Thread.sleep(100L);

		//BeanInstantiationException,注册了无法实例化的 Bean
		exec(() -> {
			AnnotationConfigApplicationContext annotionApplicationContext = new AnnotationConfigApplicationContext();
			RootBeanDefinition beanDefinition = new RootBeanDefinition();
			beanDefinition.setBeanClass(UserInterface.class);
			annotionApplicationContext.registerBeanDefinition("userInter", beanDefinition);
			annotionApplicationContext.refresh();
			annotionApplicationContext.getBean("userInter");
		});
		Thread.sleep(100L);

		//BeanCreationException,Bean 的初始化过程报错,这里是 init 方法内
		exec(() -> {
			AnnotationConfigApplicationContext annotionApplicationContext = new AnnotationConfigApplicationContext();
			annotionApplicationContext.registerBeanDefinition("userImpl",
					BeanDefinitionBuilder.rootBeanDefinition(UserImpl.class).setInitMethodName("init").getBeanDefinition());
			annotionApplicationContext.refresh();
			context.getBean("userImpl");
		});
		Thread.sleep(100L);

		//BeanDefinitionStoreException,BeanFactory 遇到非法的 BeanDefinition,这里 xml 路径不对
		exec(() -> {
			ApplicationContext context1 = new ClassPathXmlApplicationContext("/META-INF/spring-bean-exception1.xml");
			context1.getBean("user1");
		});
	}

	private static void exec(Runnable r) {
		new Thread(r).start();
	}
}

 

打印结果

ConstXiong 备案号:苏ICP备16009629号-3