Spring学习笔记–DI
依赖注入
- 构造器注入(在IOC篇已讲过)
- Setter方式注入
- 依赖注入:Set注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
实体类:
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> cards;
private Set<String> games;
private String wife;
private Properties info;
....
}
applicationContext.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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.alb.pojo.Address">
<property name="address" value="广州市"/>
</bean>
<bean id="student" class="com.alb.pojo.Student">
<!--第一种:普通值注入,value-->
<property name="name" value="Alb"/>
<!--第二种:bean注入,ref-->
<property name="address" ref="address"/>
<!--第三种:数组-->
<property name="books">
<array>
<value>Think in Java</value>
<value>Java核心技术卷I</value>
<value>Java核心技术卷II</value>
</array>
</property>
<!--第四种:List-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>打篮球</value>
</list>
</property>
<!--第五种:Map-->
<property name="cards">
<map>
<entry key="IdCard" value="121212121212121212"/>
</map>
</property>
<!--第六种:Set-->
<property name="games">
<set>
<value>王者荣耀</value>
<value>摩尔庄园</value>
</set>
</property>
<!--第七种:null值-->
<property name="wife">
<null/>
</property>
<!--第八种:properties-->
<property name="info">
<props>
<prop key="学号">1111111111</prop>
<prop key="性别">男</prop>
</props>
</property>
</bean>
</beans>
测试类:
public class MyTes {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
}
}
结果:
Student{name='Alb', address=Address{address='广州市'}, books=[Think in Java, Java核心技术卷I, Java核心技术卷II], hobbys=[听歌, 打篮球], cards={IdCard=121212121212121212}, games=[王者荣耀, 摩尔庄园], wife='null', info={学号=1111111111, 性别=男}}
-
拓展注入方式
我们可以使用p命名空间和c空间命名
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--p命名空间注入,可以直接注入属性的值:property--> <bean id="user" class="com.alb.pojo.User" p:username="Alb" p:age="20"/> <!--c命名空间注入,通过构造器注入:constructor-arg--> <bean id="user2" class="com.alb.pojo.User" c:age="20" c:username="Alb"/> </beans>