傳統 Spring 注入需在 Bean 定義中配置 <property>,且類中需聲明私有欄位並提供 getter/setter,代碼量大且易遺漏。
在 applicationContext.xml 中加入:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
此 BeanPostProcessor 會掃描所有 Bean,發現 @Autowired 即自動依類型注入。
package com.school.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.school.dao.ClasDAO;
import com.school.entity.Clas;
public class ClasServiceImpl implements ClasService {
@Autowired
private ClasDAO clasDAO; // 無需 getter/setter
// 業務方法...
}
<bean id="clasService" class="com.school.service.ClasServiceImpl">
<!-- 無需 <property> 標籤 -->
</bean>
Spring 啟動時,AutowiredAnnotationBeanPostProcessor 掃描所有 Bean,對標註 @Autowired 的欄位,在容器中尋找匹配類型的 Bean 並自動注入。若有多個同類型 Bean,可搭配 @Qualifier("beanName") 指定。