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:对应这唯一标识
        class:需要注入的全类名
     -->
    <bean id="person1" class="com.stone.dome.model.Person">
        <!--
            使用property给属性赋值 name指的是该类的属性名 ,value 值的是该属性对应的属性值
            property 赋值也称为 set  赋值 ,需要复制的属性,必须通过set方法 ,如果不提供set方法无法赋值
            并且name的值也是由该类中set方法的名字命名的 ,命名规则为set去掉,首字母小写
        -->
        <property name="name" value="zs"></property>
        <property name="sex" value="男"></property>
        <property name="age" value="23"></property>
    </bean>

    <bean id="person2" class="com.stone.dome.model.Person">
        <!--
            使用property给属性赋值 name指的是该类的属性名 ,value 指的是该属性对应的属性值
            property 赋值也称为 set  赋值 ,需要赋值的属性,必须通过set方法 ,如果不提供set方法无法赋值
            并且name的值也是由该类中set方法的名字命名的 ,命名规则为set去掉,首字母小写
        -->
        <property name="name" value="ls"></property>
        <property name="sex" value="男"></property>
        <property name="age" value="24"></property>
    </bean>

</beans>
  1. 根据bean的id获取
  //  1.获取容器
        ApplicationContext ioc= new ClassPathXmlApplicationContext("ioc.xml");

 @Test
    public void testIoc1(){
        //  2.获取bean
        Person person=(Person) ioc.getBean("person1");
        System.out.println(person);
    }
  1. 根据类型获取 (注意点 : 获取的类型在该benas只能存在一个,存在多个时会出错)
 @Test
    public void testIoc2(){
        //  2.获取bean
        Person person= ioc.getBean(Person.class);
        System.out.println(person);
    }

错误提示 (预期匹配一个 ,但是发现二个)org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘com.stone.dome.model.Person’ available: expected single matching bean but found 2: person1,person2

  1. 根据bean的id和类型获取
@Test
    public void testIoc3(){
        //  2.获取bean
        Person person= ioc.getBean("person2",Person.class);
        System.out.println(person);
    }
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐