依赖注入
1. 构造器注入
上面讲过
2. set方式注入(重点)
-
依赖注入:Set注入!
-
依赖:Bean对象的创建依赖于容器
-
注入:Bean对象中的所有属性,由容器来注入!
-
环境搭建:
1.复杂类型
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
2.真实测试对象
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private Properties info;
private String wife;
3.beans.xml
<?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="student" class="com.kuang.pojo.Student">
<!--第一种,普通值注入,value-->
<property name="name" value="冉海锋"/>
</bean>
</beans>
4.测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
}
5.完善注入信息
<bean id="address" class="com.kuang.pojo.Address">
<property name="address" value="成都"/>
</bean>
<bean id="student" class="com.kuang.pojo.Student">
<!--第一种,普通值注入,value-->
<property name="name" value="冉海锋"/>
<!--第二种:bean注入,ref-->
<property name="address" ref="address"></property>
<!--数组注入-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!--list-->
<property name="hobbys">
<list>
<value>王者荣耀</value>
<value>NBA</value>
<value>敲代码</value>
</list>
</property>
<!--map-->
<property name="card">
<map>
<entry key="身份证" value="422822199905195010"/>
<entry key="银行卡" value="6228480115249029273"/>
</map>
</property>
<!--set-->
<property name="games">
<set>
<value>LOL</value>
<value>WOW</value>
</set>
</property>
<!--null-->
<property name="wife">
<null/>
</property>
<!--Properties-->
<property name="info">
<props>
<prop key="学号">2017166123</prop>
<prop key="性别">男</prop>
<prop key="手机号">13872619392</prop>
</props>
</property>
3. 拓展方式注入
-
p命名空间注入
-
导入xml链接
xmlns:p="http://www.springframework.org/schema/p"
-
直接往属性中注入
<bean id="user" class="com.kuang.pojo.User" p:name="冉海锋" p:age="18"/>
-
-
c命名空间注入(使用构造器注入,所以需要加有参构造)
-
导入xml链接
xmlns:c="http://www.springframework.org/schema/c"
-
直接往属性中注入
<!--c命名空间注入,通过构造器注入:construct-args --> <bean id="user2" class="com.kuang.pojo.User" c:name="冉海锋" c:age="18"/>
-