Spring依赖注入
依赖注入
Spring框架的核心功能之一就是通过依赖注入的方式来管理Bean之间的依赖关系。依赖注入使用Spring框架创建对象时动态地将其所依赖的对象注入Bean中。
创建UserDao
创建UserService
添加测试代码
执行结果
构造方法依赖注入
执行结果和上面一样
基本值的依赖注入
创建一个Person类
package com.spring;
public class Person {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Spring配置文件
测试代码
测试结果
集合或数组的依赖注入
package com.spring;
import java.util.List;
public class Student {
private List<String> names;
public List<String> getNames() {
return names;
}
public void setNames(List<String> names) {
this.names = names;
}
@Override
public String toString() {
return "Student{" + "names=" + names + '}';
}
}
<?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="student" class="com.spring.Student">
<property name="names">
<list>
<value>student1</value>
<value>student2</value>
<value>student3</value>
</list>
</property>
</bean>
<bean id="student1" class="com.spring.Student">
<property name="names">
<array>
<value>student1</value>
<value>student2</value>
<value>student3</value>
</array>
</property>
</bean>
</beans>
测试代码
运行结果
Map依赖注入
package com.spring;
import java.util.Map;
public class Student {
Map<Integer, String> stuMap;
public Map<Integer, String> getStuMap() {
return stuMap;
}
public void setStuMap(Map<Integer, String> stuMap) {
this.stuMap = stuMap;
}
@Override
public String toString() {
return "Student{" + "stuMap=" + stuMap + '}';
}
}
<?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="student" class="com.spring.Student">
<property name="stuMap">
<map>
<entry>
<key>
<value>001</value>
</key>
<value>student1</value>
</entry>
<entry>
<key>
<value>002</value>
</key>
<value>student2</value>
</entry>
</map>
</property>
</bean>
</beans>
测试代码:
运行结果: