Spring EL hello worldの例

Spring EL Hello Worldの例

Spring ELはOGNLおよびJSF ELと類似しており、Beanの作成時に評価または実行されます。 さらに、すべてのSpring式は、XMLまたは注釈を介して使用できます。

このチュートリアルでは、Spring Expression Language(SpEL)を使用して、XMLとアノテーションの両方で、文字列、整数、およびBeanをプロパティに挿入する方法を示します。

1. Spring EL依存関係

Mavenpom.xmlファイルでコアSpring jarを宣言し、SpringELの依存関係を自動的にダウンロードします。

ファイル:pom.xml

    
        3.0.5.RELEASE
    

    

        
        
            org.springframework
            spring-core
            ${spring.version}
        

        
            org.springframework
            spring-context
            ${spring.version}
        

    

2. 春豆

2つの単純なBeanは、後でSpELを使用して、XMLと注釈でプロパティに値を注入します。

package com.example.core;

public class Customer {

    private Item item;

    private String itemName;

}
package com.example.core;

public class Item {

    private String name;

    private int qty;

}

3. XMLのSpring EL

SpELは#{ SpEL expression }で囲まれています。XMLBean定義ファイルの次の例を参照してください。



    
        
        
    

    
        
        
    

  1. #{itemBean} –「itemBean」を「customerBean」Beanの「item」プロパティに挿入します。

  2. #\{itemBean.name} –「itemBean」の「name」プロパティを「customerBean」Beanの「itemName」プロパティに挿入します。

4. 注釈のSpring EL

注釈モードで同等のバージョンを参照してください。

Note
アノテーションでSpELを使用するには、アノテーションを介してコンポーネントを登録する必要があります。 BeanをXMLで登録し、Javaクラスで@Valueを定義すると、@Valueの実行に失敗します。

package com.example.core;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("customerBean")
public class Customer {

    @Value("#{itemBean}")
    private Item item;

    @Value("#{itemBean.name}")
    private String itemName;

    //...

}
package com.example.core;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("itemBean")
public class Item {

    @Value("itemA") //inject String directly
    private String name;

    @Value("10") //inject interger directly
    private int qty;

    public String getName() {
        return name;
    }

    //...
}

コンポーネントの自動スキャンを有効にします。



    

注釈モードでは、@Valueを使用してSpringELを定義します。 この場合、文字列と整数の値を「itemBean」に直接挿入し、後で「itemBean」を「customerBean」プロパティに挿入します。

5. 出力

それを実行すると、XMLのSpELとアノテーションの両方に同じ結果が表示されます。

package com.example.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml");

        Customer obj = (Customer) context.getBean("customerBean");
        System.out.println(obj);
    }
}

出力

Customer [item=Item [name=itemA, qty=10], itemName=itemA]

ソースコードをダウンロード

ダウンロード–Spring3-EL-Hello-Worldr-Example.zip(6 KB)