方式一:根据id获取
由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。之前用的就是这种方式。

方式二:根据类型获取

 @Test
    public void testHelloWorld1(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        HelloWorld bean = ac.getBean(HelloWorld.class);
        bean.sayHello();
    }

方式三:根据id和类型

    @Test
    public void testHelloWorld2(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        HelloWorld bean = ac.getBean("helloworld", HelloWorld.class);
        bean.sayHello();
    }

注意的地方
当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个

当IOC容器中一共配置了两个:

    <bean id="helloworldOne" class="com.handsomeNo2.spring.bean.HelloWorld"></bean>
    <bean id="helloworldTwo" class="com.handsomeNo2.spring.bean.HelloWorld"></bean>

根据类型获取时会抛出异常:

    org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
No qualifying bean of type 'com.handsomeNo2.spring.bean.HelloWorld' 
available: expected single matching bean but found 2: helloworldOne,helloworldTwo

扩展知识

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

可以,前提是bean唯一

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

不行,因为bean不唯一

结论

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

java中,instanceof运算符用于判断前面的对象是否是后面的类,或其子类、实现类的实例。
如果是返回true,否则返回false。
也就是说:用instanceof关键字做判断时, instanceof 操作符的左右操作必须有继承或实现关系