06.ApplicationContext的getBean方法

06.ApplicationContext的getBean方法

简介

本文章将详细介绍Spring容器 ApplicationContext 通过 getBean方法 获取实例的几种方式。

1.1 方式汇总

方法定义 返回值和参数
Object getBean (String beanName) 根据beanName从容器中获取Bean实例,要求容器中Bean唯一,返回值为Object,需要强转
T getBean (Class type) 根据Class类型从容器中获取Bean实例,要求容器中Bean类型唯一,返回值为Class类型实例,无需强转
T getBean (String beanName,Class type) 根据beanName从容器中获得Bean实例,返回值为Class类型实例,无需强转

1.2 核心代码

//根据beanName获取容器中的Bean实例,需要手动强转
UserService userService = (UserService) applicationContext.getBean("userService");
//根据Bean类型去容器中匹配对应的Bean实例,如存在多个匹配Bean则报错
UserService userService2 = applicationContext.getBean(UserService.class);
//根据beanName获取容器中的Bean实例,指定Bean的Type类型
UserService userService3 = applicationContext.getBean("userService", UserService.class);

1.3 调试验证

根据Bean类型去容器中匹配对应的Bean实例,一个匹配没有报错

在这里插入图片描述

在这里插入图片描述
多个实例匹配报错:

在这里插入图片描述

在这里插入图片描述

Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.test.service.UserService' available: expected single matching bean but found 2: userService,userService2
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1262)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveBean(DefaultListableBeanFactory.java:494)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:349)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1172)
	at com.test.test.ApplicationContextTest.main(ApplicationContextTest.java:15)

猜你喜欢

转载自blog.csdn.net/ChennyWJS/article/details/132061125