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,所以也就出现了这条报错提示;

全部评论

相关推荐

02-05 08:49
已编辑
武汉大学 Web前端
野猪不是猪🐗:36k和36k之间亦有差距,ms的36k和pdd的36k不是一个概念
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务