大家好,这里是教授.F
- /**
- * 通过类型来获取容器的 bean 对象
- */
- @Test
- public void getMonsterByType() {
- ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml");
- Monster monster = ioc.getBean(Monster.class);
- System.out.println("monster=" + monster);
-
- Monster monster2 = ioc.getBean(Monster.class);
- System.out.println("monster == monster2 的值= " + (monster == monster2));
- }
- 1. 按类型来获取 bean, 要求 ioc 容器中的同一个类的 bean 只能有一个,
- 否则会抛出异常NoUniqueBeanDefinitionException
- 2. 这种方式的应用场景:比如 XxxAction/Servlet/Controller,
- 或 XxxService 在一个线程中只需要一个对象实例(单例)的情况
- 3. 老师这里在说明一下: 在容器配置文件(比如 beans.xml)中给属性赋值, 底层是通过
- setter 方法完成的, 这也是为什么我们需要提供 setter 方法的原因
"monster02" class="com.hspedu.spring.beans.Monster"> "2" index="0"/> "蜘蛛精" index="1"/> "吐口水" index="2"/> "monster03" class="com.hspedu.spring.beans.Monster"> "3" type="java.lang.Integer"/> "白骨精" type="java.lang.String"/> "白骨鞭" type="java.lang.String"/>
- 通过 index 属性来区分是第几个参数
- 2. 通过 type 属性来区分是什么类型(按照顺序)
"http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans.xsd">
"monster04" class="com.hspedu.spring.beans.Monster" - p:monsterId="4" p:name="红孩儿"
- p:skill="吐火~"
- />