はじめに:自動アセンブリとは、Springが、指定されたアセンブリルール(属性名または属性タイプ)に従って、一致する属性値を自動的に挿入することを意味します。
自動組み立てプロセス
Beanタグ属性autowireは、一般的に使用される2つの値のautowireautowire属性を構成します。
- byNameは属性名に従って挿入され、挿入された値BeanのID値はクラス属性名と同じです。
- byTypeは属性タイプに従って注入します
1.属性名による自動注入
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="person" class="iocbean.byxml.automatic.Person">
<property name="name" value="小明"></property>
</bean>
<bean id="student" class="iocbean.byxml.automatic.Student" autowire="byName">
<!--有了autowire="byName" 之后就不需要手动注入了
注入值 bean 的 id 值和类属性名称一样即可-->
<!--<property name="person" ref="person"></property>-->
</bean>
</beans>
個人クラス:
public class Person {
public String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
学生クラス:
public class Student {
private Person person;
private Person person1;
public void setPerson(Person person) {
this.person = person;
}
public void setPerson1(Person person1) {
this.person1 = person1;
}
@Override
public String toString() {
return "Student{" +
"person=" + person +
", person1=" + person1 +
'}';
}
}
テストカテゴリ:
public class DemoTest {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("iocbean/byxml/automatic/bean.xml");
Student student = context.getBean("student", Student.class);
System.out.println(student);
}
}
出力結果:
Student{person=Person{name='小明'}, person1=null}
Process finished with exit code 0
2.属性タイプに応じた自動注入
<bean id="student1" class="iocbean.byxml.automatic.Student" autowire="byType">
<!--有了autowire="byType" 之后就不需要手动注入了
所有同类型的属性都将被注入一样的值-->
<!--<property name="person" ref="person"></property>-->
</bean>
テストカテゴリ:
public class DemoTest {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("iocbean/byxml/automatic/bean.xml");
Student student1 = context.getBean("student1", Student.class);
System.out.println(student1);
}
}
出力結果:
Student{person=Person{name='小明'}, person1=Person{name='小明'}}
Process finished with exit code 0
ことがわかる
BYNAMEは、属性名に基づいて注入し、注入された値Beanのid値はクラス属性名と同じである。だから、人は、PERSON1がnull値でありました
し、byTypeは、属性タイプに応じて注入される。class属性の型のみを注入することができ、人person1のタイプはPersonであるため、両方に値があります。