Spring教程 - 弹簧属性
2018-01-09 19:06 更新
Spring教程 - 弹簧属性
我们可以将值或值列表填充到Spring xml配置文件中定义的Java bean。
以下部分显示如何将数据填充到java.util.Properties。
Java Bean
为了展示如何使用xml配置文件来填充集合属性,我们定义了一个具有四个集合属性的Customer对象。
package com.www.w3cschool.cnmon; import java.util.Properties; public class Customer { private Properties pros = new Properties(); public Properties getPros() { return pros; } public void setPros(Properties pros) { this.pros = pros; } public String toString(){ return pros.toString(); } }
Person Java Bean
package com.www.w3cschool.cnmon; public class Person { private String name; private int age; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", address=" + address + "]"; } }
属性
java.util.Properties是一个键值对structrue,我们可以使用以下语法来填充数据。
... <property name="pros"> <props> <prop key="admin">user a</prop> <prop key="support">user b</prop> </props> </property> ...
例子
Full Spring的bean配置文件。
<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="CustomerBean" class="com.www.w3cschool.cnmon.Customer"> <!-- java.util.Properties --> <property name="pros"> <props> <prop key="admin">user a</prop> <prop key="support">user b</prop> </props> </property> </bean> <bean id="PersonBean" class="com.www.w3cschool.cnmon.Person"> <property name="name" value="java2s1" /> <property name="address" value="address 1" /> <property name="age" value="28" /> </bean> </beans>
下面是加载和运行配置的代码。
package com.www.w3cschool.cnmon; 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 cust = (Customer)context.getBean("CustomerBean"); System.out.println(cust); } }
输出
Customer [ pros={admin=user a, support=user b},
Download Java2s_Spring_Properties_Collection.zip
以上内容是否对您有帮助:
更多建议: