Container的職責在於創建、配置與組裝bean,昨天我們學到了
在Spring中如何設定資料庫連線池以及如何將資料庫的資訊寫在外部設定檔中
今日將討論如何使用bean標籤中autowire屬性為bean自動配置
測試案例準備
public class User {
private String name;
private String gender = "female";
private Integer age;
private UserInfo userInfo;
private List<UserRole> userRoles;
public User() {
System.out.println("user被創建...");
}
public User(UserInfo userInfo) {
System.out.println("調用constructor:public User(UserInfo userInfo)");
this.userInfo = userInfo;
}
//getter setter toString略
}
public class UserRole {
String roleName;
//getter setter toString略
}
在<bean>標籤中有提供autowire屬性讓container幫你自動裝配自定義類的屬性
<?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="userInfo" class="com.swj.UserInfo">
<property name="title" value="經理"></property>
</bean>
<!-- 將會按照屬性名稱去找container中找id為userInfo的進行配置 -->
<bean id="user" class="com.swj.User" autowire="byName">
</bean>
</beans>
@Test
public void testDay12(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean12.xml");
System.out.println("容器啟動完成....");
User user = ioc.getBean("user",User.class);
System.out.println(user);
}
按照屬性名稱找container中對應的id
Result
<?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="userInfo" class="com.swj.UserInfo">
<property name="title" value="經理"></property>
</bean>
<!-- 將會按照屬性名稱去找container中找id為userInfo的進行配置 -->
<bean id="user" class="com.swj.User" autowire="byType">
</bean>
</beans>
Result
<?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="userInfo" class="com.swj.UserInfo">
<property name="title" value="經理"></property>
</bean>
<bean id="user" class="com.swj.User" autowire="constructor">
</bean>
</beans>
Result
<?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="userInfo01" class="com.swj.UserInfo">
<property name="title" value="總經理"></property>
</bean>
<bean id="userInfo" class="com.swj.UserInfo">
<property name="title" value="經理"></property>
</bean>
<bean id="user" class="com.swj.User" autowire="constructor">
</bean>
</beans>
Result