getBean的两种类型

Spring获取容器中bean对象的两种方式

  • Object getBean(String name);
    根据同期中Bean的id或name来获取指定的Bean,获取之后需要强制类型转换。
  • T getBean(Class requiredType);
    根据类的类型类获取Bean的实例。由于此方法为泛型方法,因此在获取Bean之后不需要进行强制类型转换。

bean.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="scope1" class="com.itheima.bean.scope.Scope" scope="singleton"></bean>

    <bean id="scope2" class="com.itheima.bean.scope.Scope" scope="prototype"></bean>
</beans>

情景:
想要演示scopet为prototype和singleton的区别,却出现了报错提示为:expected single matching bean but found 2: scope1,scope2;
在这里插入图片描述
分析:
由于调用getBean()的时候,采用了参数为泛型的方法,也就是根据类型来获取bean,此时虽然我给bean的id属性值不同,但它是根据类型来获取bean的,这时候我有两个相同类型的bean,所以也就出现了这条报错提示;

猜你喜欢

转载自blog.csdn.net/sgx5666666/article/details/105770238
今日推荐