day119 - spring-获取bean
根据id获取
上一篇的入门文章讲解的就是根据id获取bean的方式
根据类型获取
@Test public void testIOC(){ //获取ioc容器 ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml"); //获取bean Student student = ioc.getBean(Student.class); System.out.println(student); }
根据id和类型获取
@Test public void testIOC(){ //获取ioc容器 ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml"); //获取bean //Student studentOne = (Student) ioc.getBean("studentOne"); //Student student = ioc.getBean(Student.class); Student student = ioc.getBean("studentOne", Student.class); System.out.println(student); }
注意
当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个
如下:
<bean id="helloworldOne" class="com.gu.spring.HelloWorld"></bean> <bean id="helloworldTwo" class="com.gu.spring.HelloWorld"></bean>
会报错:
NoUniqueBeanDefinitionException:
总结:
根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。
/** * 获取bean的三种方式: * 1. 根据bean的id获取 * 2. 根据bean的类型获取 * 注意:根据类型获取bean时,要求ioc容器中有且只有一个类型匹配的bean * 若一个都没有,没有任何一个类型匹配的bean,抛出异常NoSuchBeanDefinitionException * 若有多个,抛出异常NoUniqueBeanDefinitionException * 3. 根据bean的id和类型获取 * 结论: * 根据类型来获取bean时,在满足bean唯一性的前提下, * 其实只看对象 instanceof指定的类型的返回结果 * 只要返回的是true就可以认定为类型匹配,能够获取到 * 即通过bean的类型或者bean所继承的类或者所实现的接口的类型都可以获取bean */
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理