依赖注入:本质Set注入
-
依赖:bean对象的创建依赖于容器
-
注入:bean对象中的所有属性,由容器注入
真实对象:
public class Student {
private String name;
private Address address;
private String[] boos;
private List<String> hobbies;
private Map<String,String> cards;
private Properties info;
}
复杂属性:
public class Address {
private String address;
}
beans配置文件(核心):
<beans>
<bean id="address" class="com.edu.zut.pojo.Address"/>
<bean id="student" class="com.edu.zut.pojo.Student">
<!-- 普通类型-->
<property name="name" value="Weining"/>
<!-- bean类型 注入对象 ref-->
<property name="address" ref="address"/>
<!-- 数组注入-->
<property name="boos">
<array>
<value>红楼梦</value>
<value>三国演义</value>
<value>水浒传</value>
</array>
</property>
<!-- List注入-->
<property name="hobbies">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>踢球</value>
</list>
</property>
<!-- map注入-->
<property name="cards">
<map>
<entry key="身份证" value="350481"/>
<entry key="QQ" value="2959"/>
</map>
</property>
<!-- prop-->
<property name="info">
<props>
<prop key="学号">123</prop>
<prop key="余额">111111</prop>
</props>
</property>
</bean>
</beans>
Test测试:
public class Mytest {
@Test
public void t1(){
ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) classPathXmlApplicationContext.getBean("student");
System.out.println(student);
}
}
拓展方式注入(不能直接使用,需要导入约束)
p命名空间
<!-- p可以直接注入属性的值-->
<bean id="user" class="com.edu.zut.pojo.UserDi" p:name="Weining" p:age="18"/>
c命名空间
<!-- c 通过构造器注入-->
<bean id="userc" class="com.edu.zut.pojo.UserDi" c:name="Weining" c:age="12"/>