Spring02_Autowire(自動注入)
byName
- 實體類Car
package com.blu.entity;
import lombok.Data;
@Data
public class Car {
private long id;
private String name;
}
- 實體類Persion
package com.blu.entity;
import lombok.Data;
@Data
public class Persion {
private long id;
private String name;
private Car car;
}
- 配置文件spring-autowire.xml
<?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="car" class="com.blu.entity.Car">
<property name="id" value="1"></property>
<property name="name" value="寶馬"></property>
</bean>
<bean id="persion" class="com.blu.entity.Persion" autowire="byName">
<property name="id" value="11"></property>
<property name="name" value="張三"></property>
</bean>
</beans>
- 測試類
package com.blu.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.blu.entity.Persion;
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-autowire.xml");
Persion persion = (Persion) applicationContext.getBean("persion");
System.out.println(persion);
}
}
- 結果
Persion(id=11, name=張三, car=Car(id=1, name=寶馬))
注:使用byName方式進行自動注入時,spring將bean的id和實體類屬性名相匹配的進行注入
byType
- 修改配置文件(修改carbean的id和persionbean的自動注入類型爲byType)
<?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="carssss" class="com.blu.entity.Car">
<property name="id" value="1"></property>
<property name="name" value="寶馬"></property>
</bean>
<bean id="persion" class="com.blu.entity.Persion" autowire="byType">
<property name="id" value="11"></property>
<property name="name" value="張三"></property>
</bean>
</beans>
- 結果
Persion(id=11, name=張三, car=Car(id=1, name=寶馬))
注:使用 byType 方式進行自動注入時,容器中只能有唯一一個Car類型的bean