2.2 通过类型获取bean
- 从IOC容器中获取bean时,除了通过id值获取,还可以通过bean的类型获取。但如果同一个类型的bean在XML文件中配置了多个,则获取时会抛出异常,所以同一个类型的bean在容器中必须是唯一的。
HelloWorld helloWorld = cxt.getBean(HelloWorld. class); |
- 或者可以使用另外一个重载的方法,同时指定bean的id值和类型
HelloWorld helloWorld = cxt.getBean(“helloWorld”,HelloWorld. class); |
2.3 给bean的属性赋值
2.3.1 依赖注入的方式
1. 通过bean的setXxx()方法赋值
Hello World中使用的就是这种方式
2. 通过bean的构造器赋值
- Spring自动匹配合适的构造器
<bean id=“book” class=“com.atguigu.spring.bean.Book” > <constructor-arg value= “10010”/> <constructor-arg value= “Book01”/> <constructor-arg value= “Author01”/> <constructor-arg value= “20.2”/> </bean > |
- 通过索引值指定参数位置
<bean id=“book” class=“com.atguigu.spring.bean.Book” > <constructor-arg value= “10010” index =“0”/> <constructor-arg value= “Book01” index =“1”/> <constructor-arg value= “Author01” index =“2”/> <constructor-arg value= “20.2” index =“3”/> </bean > |
- 通过类型区分重载的构造器
<bean id=“book” class=“com.atguigu.spring.bean.Book” > <constructor-arg value= “10010” index =“0” type=“java.lang.Integer” /> <constructor-arg value= “Book01” index =“1” type=“java.lang.String” /> <constructor-arg value= “Author01” index =“2” type=“java.lang.String” /> <constructor-arg value= “20.2” index =“3” type=“java.lang.Double” /> </bean > |
上一篇: Spring框架
下一篇: Spring框架