Spring获取bean的三种方式

Spring获取bean的三种方式
1.根据bean的id获取

根据id获取的bean一定是唯一的,但是一般需要强转对象来获取到

2.根据bean的类型获取(注意根据类型获取bean时,要求ioc容器中只有一个类型匹配的bean)

根据类型获取是用到最多的,一般在配置文件种一个类对应一个id

3.根据bean的id和类型获取

这样获取到的一定是唯一的

以下为测试代码:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="studentOne" class="com.qcw.spring.pojo.Student"></bean>
</beans>
    @Test
    public void testIOC(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");

        //根据bean的id获取
//        Student student = (Student)ioc.getBean("studentOne");

        //根据bean的类型获取
        Student student = ioc.getBean(Student.class);

        //根据bean的id和类型获取
//        Student student = ioc.getBean("studentOne", Student.class);

        System.out.println(student);
    }
}
拓展问题

如果组件类实现了接口,根据接口类型可以获取 bean 吗?
答:可以,前提是bean唯一

如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?
答:不行,因为bean不唯一

结论
根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值