Spring 3.XML自動アセンブリ、関係などの詳細

22295 ワード

1.Beanを組み立てるオプション
Springコンテナは、アプリケーション内のbeanを作成し、DIによってこれらのオブジェクト間の関係を調整します.しかし、SpringがどのBeanを作成し、どのように組み立てるかを教える必要があります.Springには3つの主要なアセンブリメカニズムがあります.-XMLで明示的に構成します.-Javaで表示構成を行います(注釈により).-暗黙的なbean発見メカニズムと自動アセンブリ.
このブログでは、XMLの高度なアセンブリについて説明します.
2.XMLオートアセンブリ
前回のブログではXMLで手動で構成されていましたが、面倒でした.Springは開発効率を高めるために自動組立を提供し、構成を簡素化しました.Springのデフォルトでは自動アセンブリはサポートされていません.使用するには、Springプロファイルのラベルのautowireプロパティを変更する必要があります.
Springサポート:
  • byName:現在のbeanのsetterスタイルのプロパティ名とbeanの名前(id)に基づいて自動的にアセンブリされます.
  • byType:現在のbeanの属性のタイプとbeanのタイプに基づいて自動組み立てを行い、IOCコンテナに複数のタイプが一致するbeanがあれば衝突する.
  • constructor(推奨しない):構造方法を使用して自動アセンブリを行い、構造方法パラメータのbyType方式に従います.
  • autodetect(破棄済み):自動選択:オブジェクトにパラメトリック構造方法がない場合、constructorの自動アセンブリ方式を自動的に選択して構造注入を行います.オブジェクトにパラメータなしの構造方法が含まれている場合は、byTypeの自動アセンブリ方式を自動的に選択してsetter注入を行います.

  • 2.1 byName自動アセンブリ
    まず2つのbeanを書きます.
  • Car類
  • public class Car {
        private String brand;
    
        public Car() { }
    
        public Car(String brand) {
            this.brand = brand;
        }
    
        public String getBrand() {
            return brand;
        }
    
        public void setBrand(String brand) {
            this.brand = brand;
        }
    
        @Override
        public String toString() {
            return "Car{" +
                    "brand='" + brand + '\'' +
                    '}';
        }
    }
  • Person類
  • public class Person {
        private String name;
        private Car car;
    
        public Person(){}
    
        public Person(String name, Car car) {
            this.name = name;
            this.car = car;
        }
    
        public Car getCar() {
            return car;
        }
    
        public void setCar(Car car) {
            this.car = car;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", car=" + car +
                    '}';
        }
    }
  • SpringXML構成
  • 
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
           xmlns:c="http://www.springframework.org/schema/c" 
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
       <bean id="car" class="demo.Car" p:brand="Audi">bean>
    
       
       
       
       <bean id="person" class="demo.Person" p:name="chen" autowire="byName">bean>
    beans>
  • テスト
  • public class Main {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans-autowire.xml");
            Person person = (Person) context.getBean("person");
            System.out.println(person);
        }
    }
    Person{name='chen', car=Car{brand='Audi'}}がコンソールに印刷されます.
    2.2 byType自動組立
  • SpringXML構成
  • 
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
           xmlns:c="http://www.springframework.org/schema/c" 
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
       
       <bean id="carcarcarcar" class="demo.Car" p:brand="Audi">bean>
    
       
       
       
       <bean id="person" class="demo.Person" p:name="chen" autowire="byType">bean>
    beans>

    car bean構成におけるid属性を変更した後も、byTypeで組み立てることができます.同じ結果が制御印刷されるPerson{name='chen', car=Car{brand='Audi'}}.
    2.3 constructor自動組立
  • SpringXML構成
  • 
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
           xmlns:c="http://www.springframework.org/schema/c"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
       
       <bean id="carcarcarcar" class="demo.Car" p:brand="Audi">bean>
       <bean id="namenamename" class="java.lang.String" c:value="chen">bean>
    
       <bean id="person" class="demo.Person" autowire="constructor">bean>
    beans>

    修正idはbeanのsetterと異なる後、すなわち
    修正id後もconstructor自動アセンブリで取得でき、構造方法のパラメータbyTypeによる自動アセンブリであることが検証できる.
    3.Bean間の関係
    ここでの関係はbeanの構成間の関係を指し,実際の意味でクラスとクラス間の継承と依存を指すのではない.
    3.1継承(parent)
    beanのparent属性を使用して継承beanの構成を指定します.1.子beanは親beanから継承された構成を上書きできます.2.親beanをテンプレートとして、のabstract属性をtrueに設定できます.Springはこのbean 3.autowire、abstractなどの属性をインスタンス化しません.4.親beanのclass属性を無視して、子beanに自分のクラスを指定することができます.同じプロパティ構成を共有しますが、abstractをtrueに設定する必要があります.
  • SpringXML構成
  • 
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
           xmlns:c="http://www.springframework.org/schema/c"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
       <bean id="car1" class="demo.Car" p:brand="BMW" abstract="true">bean>
       <bean id="car2" class="demo.Car" parent="car1">bean>
    
       <bean id="person" class="demo.Person" p:name="chen" p:car-ref="car2">bean>
    beans>

    このコードには、2つの属性abstract="true"parent="car1"が表示されます.
    3.2依存(depend-on)
    depends-on属性は指定されず、IOCコンテナのデフォルトインスタンス化の順序はbeanのプロファイル内の順序でインスタンス化されます.指定すると、依存するbeanは、このbeanがインスタンス化される前に作成されます.複数の依存beanを指定できます.-SpringXML構成
    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        
        <bean id="person" class="demo.Person" p:name="chen" p:car-ref="car2 car1">bean>
    
        <bean id="car1" class="demo.Car" p:brand="BMW">bean>
        <bean id="car2" class="demo.Car" parent="car1">bean>
    beans>

    4.Beanの役割ドメイン(scope)
    beanに定義されたプロパティscope.デフォルトはsingletonです.たとえば、です.
    アクティブドメイン
    説明
    singleton
    Spring IoCコンテナ全体でsingletonを使用して定義されたBeanには1つのインスタンスしかありません.
    prototype
    プロトタイプモードでは、コンテナのgetBeanメソッドでprototype定義のBeanを取得するたびに、新しいBeanインスタンスが生成されます.
    request
    HTTPリクエストごとにrequest定義を使用するBeanには、新しいインスタンスが生成されます.つまり、HTTPリクエストごとに異なるBeanインスタンスが生成されます.この役割ドメインは、WebアプリケーションでSpringを使用する場合にのみ有効です.
    session
    HTTPセッションごとにセッション定義を使用するBeanに新しいインスタンスが生成されます.この役割ドメインは、WebアプリケーションでSpringを使用する場合にのみ有効です.
    globalSession
    各グローバルのHTTPセッションでは、セッションを使用して定義されたBeanが新しいインスタンスを生成します.典型的にはportlet contextを使用する場合にのみ有効です.この役割ドメインは、WebアプリケーションでSpringを使用する場合にのみ有効です.
    5.外部属性ファイルの使用
    次のように表示されます.
  • パラメータは、ある段階で定数
  • である
  • パラメータは、異なる段階で
  • を変更する必要がある場合がある.
    この場合Springは元素を導入することができる.次に、データベースに接続した例を示します.
    contextネーミングスペース(xmlns:context="http://www.springframework.org/schema/context"で宣言)
  • SpringXML構成
  • <context:property-placeholder location="classpath:db.properties"/>

    もう1つ:
  • SpringXML構成
  • <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>db.propertiesvalue>
            list>
        property>
    bean>

    locationに複数のファイルがある場合は順次ロードされますが、前のファイルの属性名と後のファイルの属性名が同じであれば、最終的には後のファイルの値が取得されます.したがって、異なるファイルのプロパティ名の重複は避ける必要があります.
  • db.propertiesプロファイル
  • #jdbc  
    user=root
    password=root
    driverClass=com.mysql.jdbc.Driver
    jdbcUrl=jdbc:mysql:///library
  • SpringXML構成
  • 
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${user}" >property>
        <property name="password" value="${password}">property>
        <property name="driverClass" value="${driverClass}">property>
        <property name="jdbcUrl" value="${jdbcUrl}">property>
    bean>

    ここではEL式のような${}形式が現れる.
    Springコンテナでは、最大1つのPropertyPlaceholderConfigurerまたはを定義できます.残りはSpringによって無視されます.