Spring学習ノート-BeanFactory容器
5355 ワード
BenFactory容器はSpringの重要な容器で、後ろの全ての容器はこの容器を継承しています.その中でBenFactoryの重要な実現クラスはDefault Listable BeanFactoryです.BenFactory容器の初期化手順は以下の通りです.は、私たちビーンが定義するリソースの位置を特定するための抽象的なリソースを設定します.ここでは、Class pathResourceリソースを使用しています.実は、Class pathResourceというリソースは主に二つの属性があります.一つはパス、もう一つはfile、path指定ファイルの位置を設定し、java.io.Fileという種類で指定された配置ファイルの位置を接続します. BenFactoryを新たに作成し、BenDefinitionを保存します.ここではBenFactoryの一つで、DefaultListable BenFactoryを実現します. XmlBenFactoryReaderを新たに作成し、Class pathResourceをBean definitionに読み込むために使用します. は、XmlBenFactoryReader内のloadBenDefinition方法を呼び出して、読み取った情報をBenFactoryに注入する. ケース
package com.zbt.springbean_day01;
/**
* Created by luckyboy on 2018/8/18.
*/
public class Student {
private int age;
private String name;
public Student(){}
public Student(int age,String name){
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
spring-config.xmlプロファイル
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="student" class="com.zbt.springbean_day01.Student">
<property name="age" value="10">property>
<property name="name" value="Zou">property>
bean>
beans>
テストファイル @Test
public void test2(){
//1、
ClassPathResource resource = new ClassPathResource("contextConfig.xml");
//2、 IOC
DefaultListableBeanFactory container = new DefaultListableBeanFactory();
//3、 BeanDefinition BeanDefinition , XmlBeanDefinitionReader
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(container);
//4、
reader.loadBeanDefinitions(resource);
Student stu = (Student) container.getBean("student");
System.out.println(stu.getName());
}