di:依赖注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
构造器注入
前面已经介绍过,参考spring(三):配置文件配置
set方式注入【重点】
环境搭建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package com.hanser.pojo;
import java.util.*;
@Data public class Student { private String name; private Address address; private String[] books; private List<String> hobbies; private Map<String, String> card; private Set<String> games; private Properties info; private String wife; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| <?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="address" class="com.hanser.pojo.Address"> <property name="address" value="大连"/> </bean>
<bean id="student" class="com.hanser.pojo.Student"> <property name="name" value="憨色"/> <property name="address" ref="address"/> <property name="books"> <array> <value>博丽灵梦</value> <value>魂魄妖梦</value> <value>赫卡提亚</value> <value>帕秋莉</value> </array> </property> <property name="hobbies"> <list> <value>无人区</value> <value>去剪海的日子</value> <value>主播女孩重度依赖</value> </list> </property> <property name="card"> <map> <entry key="han" value="雷姆"/> <entry key="ser" value="拉姆"/> <entry key="c" value="艾米莉亚"/> </map> </property> <property name="games"> <set> <value>Muse Dash</value> <value>Apex</value> <value>DokiDoki</value> </set> </property> <property name="wife"> <null/> </property> <property name="info"> <props> <prop key="游戏">Muse Dash</prop> <prop key="学号">1234567</prop> <prop key="姓名">hanser</prop> </props> </property> </bean>
</beans>
|
拓展
我们可以使用p命名空间和c命名空间进行注入
1 2
| xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
|
- p命名空间:p(property),通过set注入注入
1 2
| <bean id="user1" class="com.hanser.pojo.User" p:age="18" p:name="hanser" scope="prototype"/>
|
- c命名空间:c(constructor-args),通过构造器注入
1 2
| <bean id="user2" class="com.hanser.pojo.User" c:age="28" c:name="憨色"/>
|
bean作用域
- 单例模式(Spring默认机制),无论调用多少次getBean方法,因为内存中只有这一个bean,所以取出来的都是一个对象
1
| <bean id="user1" class="com.hanser.pojo.User" scope="singleton"/>
|
- 原型模式:每次从容器中get的时候,都会产生一个新对象!
1
| <bean id="user1" class="com.hanser.pojo.User" scope="prototype"/>
|
- 其余的request、session、application、这些只能在web开发中使用到