获取bean的三种方式和注意事项

获取bean的三种方式和注意事项

spring-ioc.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="studentOne" class="com.atguigu.spring.pojo.Student"></bean>

</beans>

①方式一:根据bean的id获取

  • 由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。 上个实验中我们使用的就是这种方式。
public class IOCByXMLTest {

    @Test
    public void testIOC(){
        //获取IOC容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
        //获取bean
        Student studentOne = (Student) ioc.getBean("studentOne");
        System.out.println(studentOne);
    }
}

②方式二:根据bean的类型获取(常用)

  • IOC容器中一个类型的bean只需要配置一次
public class IOCByXMLTest {

    @Test
    public void testIOC(){
        //获取IOC容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
        //获取bean
        Student studentOne = ioc.getBean(Student.class);
        System.out.println(studentOne);
    }
}

③方式三:根据bean的id和类型

public class IOCByXMLTest {

    @Test
    public void testIOC(){
        //获取IOC容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
        //获取bean
        Student studentOne = ioc.getBean("studentOne", Student.class);
        System.out.println(studentOne);
    }
}

④注意

  • 当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个
IOC容器中一共配置了两个:
<bean id="studentOne" class="com.atguigu.spring.pojo.Student"></bean>
<bean id="studentTwo" class="com.atguigu.spring.pojo.Student"></bean>
根据类型获取时会抛出异常:

当IOC容器中没有任何一个类型匹配的bean,则会抛出如下异常:

⑤扩展

如果组件类实现了接口,根据接口类型可以获取 bean 吗?

可以,前提是 bean 唯一,即该接口只能有一个实现类

 

public class IOCByXMLTest {

    @Test
    public void testIOC(){
        //获取IOC容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
        //获取bean
        Person studentOne = ioc.getBean(Person.class);
        System.out.println(studentOne);
    }
}

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

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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值