集合屬性之Map屬性和properties屬性
阿新 • • 發佈:2019-01-02
一:配置Map屬性
1.java.util.Map通過<map>標籤定義,<map>標籤裡可以使用多個<entry>作為子標籤,每個裡面都包含一個鍵和一個值
2.必須在key屬性定義鍵。
3.因為鍵和值的型別沒有限制,所以可以自由的為他們指定<value>,<value-ref>,<bean>或null元素。
4.可以將Map的鍵和值作為<entry>的屬性定義,簡單的常量使用key和value定義,bean引用通過key-ref和value-ref來定義
<!-- 配置Map屬性值--> <bean id="newPerson" class="com.collection.dhx.NewPerson"> <property name="name" value="Jike"></property> <property name="age" value="23"></property> <property name="cars"> <!--使用map節點及map的entry子節點配置map型別的成員變數 key:代表鍵,自主定義 value-ref:代表指定的bean --> <map> <entry key="AA" value-ref="car"></entry> <entry key="BB" value-ref="car2"></entry> <entry key="BB"> <bean id="car" class="com.dhx.Car"> <property name="brand" value="heilong"></property> <property name="corp" value="yunnan"></property> <property name="maxSpeed" value="1234"></property> </bean> </entry> </map> </property> </bean>
2.如何配置 properties屬性值
1.建立DataSource類
package com.collection.dhx; import java.util.Properties; public class DataSource { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } @Override public String toString() { return "DataSource [properties=" + properties + "]"; } }
2.在applicationContext.xml中配置bean
<!--配置properties屬性值 --> <bean id="dataSource" class="com.collection.dhx.DataSource"> <property name="properties"> <!--使用props節點及prop子節點為properties屬性賦值 --> <props> <prop key="user">root</prop> <prop key="password">1234</prop> <prop key="jdbcurl">jdbc:mysql:///test</prop> <prop key="driverClass">com.mysql.jdbc.driver</prop> </props> </property> </bean>
3.最後在Main類列印
package com.collection.dhx;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource=(DataSource) ctx.getBean("dataSource");
System.out.println(dataSource);
}
}