Spring定義と組み立てBean


前のブログでSpringの中のIOCとAOPについて議論しましたが、この記事ではSpringがどのようにIOCを実現しているのかをコードで示しています.このブログでは、SpringでJava Beanを定義し、搭載する方法を紹介します.
ビジネスシーン
まだ人が運転する例です.まず、一つのカールインターフェースを定義し、二つのBenzとBMWを実現し、その後一つのPerson類、Person類依存カルボインターフェースを定義する.
public interface Car {
    void go();
}
public class Benz implements Car {
    public void go() {
        System.out.println("benz go......");
    }
}
public class BMW implements Car {
    public void go() {
        System.out.println("bmw go......");
    }
}
public class Person {
    String name = "";

    Car car = null;
    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    public Person(String name) {
        this.name=name;
    }

    public void Drive(){
        System.out.println(name+" is driving ...");
        car.go();
    }
}
Personクラスではcarオブジェクトはこのクラスの依存対象であり、構造法によってPersonクラスに注入する必要があることが見られます.以上のコードはまだSpringの影がありません.次にSpringがどのように注入されているかを見てください.
Spring依存を追加
現在は多くの項目がmavenで管理されていますが、本プロジェクトもそうです.私はpom.xmlに依存ノードを入れます.
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-coreartifactId>
    <version>3.2.6.RELEASEversion>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-beansartifactId>
    <version>3.2.6.RELEASEversion>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>3.2.6.RELEASEversion>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-context-supportartifactId>
    <version>3.2.6.RELEASEversion>
dependency>
これらのdependencyノードをpom.xmlファイルのdependenciesノードに入れて、eclipseは自動的に関連するパケットをデフォルトの場所にダウンロードします.
手動定義と組立ビーム
プロジェクトのルートディレクトリにbean.xmlという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-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="car" class="kite.springProj1.BMW" />
    <bean id="tom" class="kite.springProj1.Person">
        <constructor-arg value="Tom" />
        <property name="car" ref="car" />
    bean>
beans>
上のXMLファイルは、まずIDがcarであるbeanを定義し、また一つのidがtomであるbeanを定義し、carはtomとしての依存性を定義し、の方式により、手動でtomのcar属性に組み立てられた.
アプリケーション間の連携関係を作成する行為をアセンブリ(wiring)と呼び、これもオブジェクト注入に依存する本質である.次に、アプリケーションのコンテキストオブジェクトをmainメソッドに実装し、beanのtomノードを取得します.
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Person tom=(Person) context.getBean("tom");
        tom.Drive();
    }
}
プログラムを実行し、出力結果は以下の通りです.
Tom is driving ...
bmw go......
自動組み立て
もう一回繰り返して、アプリケーションオブジェクト間の連携関係を作成する行為は、実装対象ではなく、組立(wiring)と呼ばれます.上のxmlファイルでは、を通じて依存対象を組み立てましたが、アプリケーションが発展するにつれて、xmlプロファイルはますます複雑になります.私たちはref="car"を通して、idをcarのbeanに関連付けるという方式はもう遅れています.Springがどのように自動組立beanを実現するかを紹介します.
自動組立のタイプ
Springの4つの組み立て戦略は、本稿の複雑性を低減するために、一般的な2つの戦略を紹介します.byName方式とbyType方式です.名前の通り、byName方式とは属性の名前がbeanのidと同じかどうかを見ることであり、この例ではPerson類にcarという属性があり、このクラスまたは属性を自動組立かつ組み立て戦略がbyNameに設定すれば、Springはidをcar(同名でなければならない)のbeanに探すことができる.byType方式は比較タイプが同じですか?本例では、Person類またはPerson類のcar属性を自動組立かつ組立戦略がbyTypeに設定すると、car属性はCarタイプであるため、Springは自動組立を行う際に、Carまたはそのサブタイプのbeanを探します.
XMLを使って自動組立を実現します.
コードを修正して、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-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="car" class="kite.springProj1.BMW" />
    <bean id="tom" class="kite.springProj1.Person" autowire="byName">
        <constructor-arg value="Tom" />
    bean>
beans>
Person類は何も修正する必要がない.まず、私は行のコードを抜きました.手作りの方式ですから.そして、私はidをtomのbeanとして属性autowire="byName"を追加し、名前による自動組立依存に設定します.Personオブジェクトを取得する時、Personの属性名はすべて特殊な意味があります.SpringはPerson類にcarという属性があることを監視し、配置ファイルの中にcarというidのbeanを見つけました.すると、Personのcar属性に自動的に組み立てられました.
上のコードはspringを設置して一つのbeanを自動的に組み立てるだけで、全体の標準的な組み立て方式を設定することもできます.springは全てのbeanに対してこの方式を使って自動的に組み立てることができます.ノードにdefault-autowire属性を設定すれば良い.この属性のデフォルト値はnoです.

<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-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd"
        default-autowire="byType">

    <bean id="car" class="kite.springProj1.BMW" />
    <bean id="tom" class="kite.springProj1.Person">
        <constructor-arg value="Tom" />
    bean>
beans>
全体的なデフォルトの組み立て方式が設定されているが、全てのbeanが他の組み立て方式を使用して自動組立できないという意味ではなく、各beanは依然として別の組み立て方式を指定して全体を覆う方式が可能である.
注解による自動組立
springはまた、注釈を用いてbeanを組み立てる属性をサポートしています.注釈を使って組み立てるには、まず配置ファイルで開く必要があります.bean.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-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config />

    <bean id="car" class="kite.springProj1.BMW" />
    <bean id="tom" class="kite.springProj1.Person">
        <constructor-arg value="Tom" />
    bean>
beans>
私はbeanで自動組立方式を宣言していません.全体の自動組立方式も声明していません.ただ一行を追加して、springに注釈を使ってbeanの依存性を組み立てたいと言います.その後Person類を少し修正して、carのsetter方法に@Autowired注解を加えて、Springにこの属性を自動組立するように通知します.コードを再起動しても出力結果は変わりません.
@Autowired
public void setCar(Car car) {
    this.car = car;
}
springがbeanの一例を作成すると、ある属性が@Autowired注釈を使用していることが発見されると、byTypeの方式を使用して組み立てることを試みる.@Autowiredは、setter方法だけでなく、プライベート属性も表示することができます.
上記のすべてのコードの中で、私達は配置ファイルでorg.zdk.springProj1.BMW類をPerson類として使用しています.もし業務需要のため、Person類はBMW車を運転する必要がないので、ベンツ車を運転しました.この構成をorg.zdk.springProj1.Benzに変更すればいいです.Javaコードを変更する必要がないです.これはSpringがIOC容器としての強みです.
また、スプリングは自動組立を表示する三つのタイプの注釈をサポートしています.@Autowired以外に、JSR-330の@Inject注釈とJSR-250の@Resource注釈もあります.彼らの役割は同じです.