1.构造器注入
前面已经说过
2.Set方式注入【重点】
- 依赖注入:本质是Set注入
依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器来注入
【环境搭建】
1.复杂类型
public class Address {
private String address;
public Address() {
}
public Address(String address) {
this.address = 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> hobbies;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
}
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.hui.pojo.Student">
<!-- 第一种,普通值注入,value-->
<property name="name" value="hui"/>
</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());
}
}
完善注入信息
<!-- 第一种,普通值注入,使用value-->
<property name="name" value="hui"></property>
<!-- 第二种,bean注入,使用ref-->
<property name="address" ref="address"/>
<!-- 第三种,数组注入,ref-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!-- 第四种,List注入-->
<property name="hobbies">
<list>
<value>唱</value>
<value>跳</value>
<value>rap</value>
</list>
</property>
<!-- 第五种,Map注入-->
<property name="card">
<map>
<entry key="身份证" value="123456"/>
<entry key="驾驶证" value="789123"/>
</map>
</property>
<!-- 第六种,Set注入-->
<property name="games">
<set>
<value>LOL</value>
<value>Dota2</value>
<value>CF</value>
</set>
</property>
<!-- 第七种,null值注入-->
<property name="wife">
<null/>
</property>
<!-- 第八种,Properties注入-->
<property name="info">
<props>
<prop key="driver">123456</prop>
<prop key="url">123456</prop>
<prop key="username">123456</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
3.拓展方式注入
我们可以使用p命名空间和c命名空间注入
简单使用:
<!-- p命名空间注入,可以直接输入属性的值:property-->
<bean id="user" class="com.hui.pojo.User" p:name="hui"/>
<!-- c命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="com.hui.pojo.User" c:name="hui"/>
注意:p命名空间和c命名空间不能直接使用,需要导入xml约束!
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"