首页 > 技术文章 > Spring(二) HelloWorld 细节 及常见错误

wdh01 2020-08-11 23:07 原文

  在之前的文章里 我们简单介绍了 Spring 的 HelloWorld ,接下来我们总结下 相关细节;

/**
* IOC HelloWorld 细节:
* 1、ApplicationContext IOC 容器接口
* 2、组件的创建,由容器进行
* 3、容器中对象的创建在容器创建时就已经创建完毕;
* 4、同一个组件在 IOC 容器内是单实例的,且在容器创建时就创建完成;
* 5、IOC 容器在创建组件时,会利用 SET() 方法进行赋值
* 
*/

 

初学者常见错误:

1、找不到对应的组件;

代码片段:

// 容器创建对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        Person p1 = (Person) ctx.getBean("p03");

 Spring 配置文件片段

<!-- 注册 Person 对象,一个 bean 标签注册一个组件
    class:注册组件的全类名
    id:组件的唯一标识 
     -->
    <bean id="p01" class="org.wdh01.bean.Person">
    <!--  使用 property 为组件赋值  
    name 属性名 value 属性值-->
    <property name="lastName" value="令狐冲"></property>
    <property name="age" value="29"></property>
    <property name="gender" value="男"></property>
    <property name="email" value="linghc@huashan.com"></property>
    </bean>
    <bean id="p02" class="org.wdh01.bean.Person">
        <property name="lastName" value="田伯光"></property>
    </bean>

报错信息:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'p03' is defined

测试代码片段要获取 ID =“p03” 的组件,但 Spring 配置文件并无此唯一标识的 bean ,所以在获取指定ID 的bean 时,切记要保证 Spring 配置文件的 bean 存在;

2、组件不唯一

代码片段

Person p2 = (Person) ctx.getBean(Person.class);
        System.out.println(p2);

Spring 配置文件片段

<bean id="p01" class="org.wdh01.bean.Person">
    <!--  使用 property 为组件赋值  
    name 属性名 value 属性值-->
    <property name="lastName" value="令狐冲"></property>
    <property name="age" value="29"></property>
    <property name="gender" value="男"></property>
    <property name="email" value="linghc@huashan.com"></property>
    </bean>
    <bean id="p02" class="org.wdh01.bean.Person">
        <property name="lastName" value="田伯光"></property>
    </bean>

报错信息

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.wdh01.bean.Person] is defined: expected single matching bean but found 2: p01,p02

当配置文件存在同一类型 bean 的组件是多个时,不能使用 ctx.getBean(Person.class); 来获取对象。需要使用指定 bean id 或者 bean id + 组件类型的方法获取 bean 来保证程序能找到唯一的组件;

 

推荐阅读