spring Dependency Injection
依赖:指bean对象的创建依赖与容器
注入:指bean对象所依赖的资源,由容器来设置和装配
-
方式一:构造器注入
无参构造,需要无参构造器
<bean id="user" class="com.wpz.User"> <property name="str" value="Hello come on!"/> <!-- collaborators and configuration for this bean go here --> </bean>
-
通过下标赋值 <constructor-arg index ="0" value="xxx"/>
-
通过类型 ,不建议使用 <constructor-arg type="java.lang.string" value="xxx"/>
-
直接通过参数名来设置 <constructor-arg name="username" value="xxx"/>
- 方式二:set注入
要求被注入的属性,必须有set方法。如果是Boolean类型,没有set方法,是is
实体类
public class Student { private String name; private String wifi; private Adress adress; private String[] books; private List<String> hobbies; private Map cards; private Properties prop; private Set<String> games; public void setName(String name) { this.name = name; } public void setWifi(String wifi) { this.wifi = wifi; } public void setAdress(Adress adress) { this.adress = adress; } public void setBooks(String[] books) { this.books = books; } public void setHobbies(List<String> hobbies) { this.hobbies = hobbies; } public void setCards(Map cards) { this.cards = cards; } public void setProp(Properties prop) { this.prop = prop; } public void setGames(Set<String> games) { this.games = games; }
配置文件:
<bean id="addr" class="com.wpz.Adress"> <property name="addr" value="DaLian"></property> </bean> <bean id="stu" class="com.wpz.Student"> <!-- 第一种 普通值注入--> <property name="name" value="wpz"/> <!-- 第二种 bean注入 ref--> <property name="adress" ref="addr"/> <!-- 数组--> <property name="books"> <array> <value>红楼梦</value> <value>周易</value> <value>吕氏</value> </array> </property> <!-- list--> <property name="hobbies"> <list> <value>听歌</value> <value>看戏</value> </list> </property> <!-- map--> <property name="cards"> <map> <entry key="Id" value="220714199912121234"></entry> <entry key="stuId" value="20082041"></entry> </map> </property> <!-- set--> <property name="games"> <set> <value>QQQ</value> <value>WWW</value> <value>EEE</value> </set> </property> <!-- properties--> <property name="prop"> <props> <prop key="name">root</prop> <prop key="pwd">admin</prop> </props> </property> <!-- null--> <property name="wifi"> <value>null</value> </property> </bean>
- 方式三:P命名 和 C命名注入
配置:在头文件加入约束文件
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
使用:
<!-- 需要无参构造--> <bean id="usr" class="com.wpz.User" p:str="wwwpz"></bean> <!-- 需要有参构造--> <bean id="usr" class="com.wpz.User" c:str="ddd" autowire="byName"></bean>