1. 程式人生 > >Spring XML配置注入Bean屬性舉例

Spring XML配置注入Bean屬性舉例

Spring <Map>元素用來儲存多個鍵值對屬性,型別為java.util.Map;他的子標籤<entry>用來定義Map中的鍵值實體,下面舉例說明;

Article.java

這個article class有一個屬性是作者聯名資訊,使用序號和作者名來構成一個Map屬性.

import java.util.*;

public class Article

private String title;

private Map<String, String> authorsInfo;

public void setTitle(String title) {

this.title = title;

}

public String getTitle() {

return title;

}

public void setAuthorsInfo(Map<String, String> authorsInfo) {

this.authorsInfo = authorsInfo;

}

public Map<String, String> getAuthorsInfo() {

return authorsInfo;

}

spring-beans.xml: 

<map>元素用於提供具體的實體鍵值配置,通過<entry>將序號和作者名稱進行繫結注入。

<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-2.5.xsd">

<bean id="article" class="Article">

<property name="title" value="RoseIndia"/>

<property name="authorsInfo"> 

<map>

<entry key="1" value="Deepak" />

<entry key="2" value="Arun"/>

<entry key="3" value="Vijay" />

</map>

</property>

</bean>

</beans>

RunDemoMain.java

測試主程程式碼;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.*;

public class AppMain 

{

public static void main( String[] args )

{

ApplicationContext appContext = 

new ClassPathXmlApplicationContext(new String[] {"spring-beans.xml"});

Article article = (Article)appContext.getBean("article");

System.out.println("Article Title: "+article.getTitle());

Map<String, String> authorsInfo = article.getAuthorsInfo();

System.out.println("Article Author: ");

for (String key : authorsInfo.keySet()) {

System.out.println(key + " : "+(String)authorsInfo.get(key));

}

}

輸出結果如下:

Article Title: RoseIndia

Article Author:

1 : Deepak

2 : Arun

3 : Vijay

轉自:http://www.txdnet.cn/log/20221059000001.xhtm