DI依赖注入(Dependency Injection)
1.1 构造器注入
详情见我的上一篇博客https://blog.csdn.net/weixin_46976101/article/details/109363663 ┗|`O′|┛
1.2 set方式注入(重点)
-
依赖注入:Set注入!
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器注入
-
环境搭建
- 复杂类型
package com.wangxu.POJO; public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Address{" + "address='" + address + '\'' + '}'; } }
- 真实测试对象
package com.wangxu.POJO; import java.util.*; public class Student { private String name; private Address address; private String [] book; private List<String> hobbys; private Map<String, String> card; private Set<String> games; private String girlfriend; private Properties info; //节省空间此处省略get,set,tostring() }
八种注入方式!(重点!重点!重点!重点!重点!重点!重点!重点!)
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="address" class="com.wangxu.POJO.Address"> <property name="address" value="黄陵"/> </bean> <bean id="student" class="com.wangxu.POJO.Student"> <!--第一种,普通值注入,value--> <property name="name" value="王旭"/> <!--第二种,bean注入,ref--> <property name="address" ref="address"/> <!--第三种,数组注入--> <property name="book"> <array> <value>红楼梦</value> <value>西游记</value> <value>水浒传</value> <value>三国演义</value> </array> </property> <!--第四种,List注入--> <property name="hobbys"> <list> <value>听歌</value> <value>敲代码</value> <value>看电影</value> </list> </property> <!--第五种,Map注入--> <property name="card"> <map> <entry key="身份证" value="546768354564654"/> <entry key="银行卡" value="4566568765456498"/> </map> </property> <!--第六种,Set注入--> <property name="games"> <set> <value>LOL</value> <value>COC</value> </set> </property> <!--第七种,空值注入--> <property name="girlfriend"> <null/> </property> <!--第八种,Properties注入--> <property name="info"> <props> <prop key="学号">18060208118</prop> <prop key="手机号">15114916289</prop> <prop key="性别">男</prop> </props> </property> </bean> </beans>
1.3 C命名空间和P命名空间注入
1.3.1P命名空间注入
xmlns:p="http://www.springframework.org/schema/p"
<!--P命名空间注入,可以直接注入属性的值-->
<bean id="user" class="com.wangxu.POJO.User" p:name="王旭" p:age="21"/>
1.3.2 C命名空间注入
xmlns:c="http://www.springframework.org/schema/c"
<!--C命名空间注入,通过构造器注入属性的值-->
<bean id="user2" class="com.wangxu.POJO.User" c:name="王旭" c:age="21"/>
注意点:P命名空间和C命名空间不能直接使用,需要导入xml约束!