本文將詳細介紹如何在 Spring 框架中使用 autowire="byName" 實現依 Bean 名稱自動裝配,透過完整的程式碼範例幫助您快速掌握這項技術。
<bean> 元素的 autowire 屬性負責自動裝配 Bean 的屬性,可大幅減少配置程式碼,使結構更清晰。但需注意:啟用自動裝配後,無法直接從配置文件看出 Bean 依賴哪些屬性。
package com.importnew;
public class User {
private String name = "test";
private String sex = "男";
private int age = 29;
private String tel = "123456789";
// Getter/Setter 方法省略
@Override
public String toString() {
return "User [name=" + name + ", sex=" + sex + ", age=" + age + ", tel=" + tel + "]";
}
}
package com.importnew;
public class TestUtil {
private User user;
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.importnew.User" />
<bean id="testUtil" class="com.importnew.TestUtil" autowire="byName" />
</beans>
關鍵點:autowire="byName" 會尋找與 TestUtil 中 user 屬性同名的 Bean (即 id="user") 並自動注入。
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.importnew.TestUtil;
import com.importnew.User;
public class TestSpring {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
TestUtil testUtil = (TestUtil) context.getBean("testUtil");
User user = testUtil.getUser();
System.out.println("年齡: " + user.getAge());
System.out.println("姓名: " + user.getName());
}
}
UnsatisfiedDependencyException。解決方法是混合使用手動裝配 (<property>) 指定具體 Bean。autowire="byType" 即可。自動裝配能簡化配置,但需權衡可讀性與靈活性。實務上建議:簡單場景用 byName,複雜依賴關係改用显式配置或 @Autowired 註解更清晰可控。