Spring 依賴注入(DI)核心由 BeanFactory 管理組件及依賴關係。注入方式主要有二:
public interface StudentService {
Student getStudent(String id);
void createStudent(Student stu);
Set getCompletedCourses(Student stu);
}
public interface CourseService {
Course getCourse(String id);
void createCourse(Course course);
Set getAllCourses();
void enrollStudentInCourse(Course course, Student stu) throws CourseException;
}
public class StudentServiceImpl implements StudentService {
private StudentDao stuDao;
// 構造器注入
public StudentServiceImpl(StudentDao sDao) { this.stuDao = sDao; }
// Setter 注入
public void setStudentDao(StudentDao sDao) { this.stuDao = sDao; }
// ... 方法委托 stuDao
}
public class CourseServiceImpl implements CourseService {
private CourseDao courseDao;
private StudentService studentService;
private int maxStudents;
// 構造器注入核心依賴
public CourseServiceImpl(CourseDao courDao) { this.courseDao = courDao; }
// Setter 注入輔助依賴
public void setStudentService(StudentService stuService) { this.studentService = stuService; }
public void setMaxStudents(int maxStudents) { this.maxStudents = maxStudents; }
// ... 業務邏輯
}
<beans>
<bean id="studentDao" class="com.springinaction.service.training.StudentDaoImpl"/>
<bean id="courseDao" class="com.springinaction.service.training.CourseDaoImpl"/>
</beans>
預設 singleton="true",容器僅維護單一實例。若需每次獲取新實例,設 singleton="false"(謹慎使用,避免資源耗盡)。
<bean id="courseService" class="com.springinaction.service.training.CourseServiceImpl">
<property name="maxStudents"><value>30</value></property>
<property name="studentService">
<ref bean="studentService"/>
</property>
</bean>
<bean id="studentService" class="com.springinaction.service.training.StudentServiceImpl">
<constructor-arg ref="studentDao"/>
</bean>
<property><bean class="..."/></property>,但無法重用。<list>、<set>、<map>、<props> 支援值與 Bean 引用混合。index 或 type 屬性精確匹配多參建構子。XMLBeanFactory:簡單,從 InputStream 載入。ClassPathXmlApplicationContext:從類路徑載入,常用於獨立應用。FileSystemXmlApplicationContext:從文件系統載入。XmlWebApplicationContext:Web 環境專用。Spring DI 以 BeanFactory 為核心,支援構造器與 Setter 靈活組合,配合豐富的 XML 裝配語法,實現組件鬆耦合、易測試、易配置的企業級應用基石。