Spring教程 - 彈簧屬性

2018-01-09 19:06 更新

Spring教程 - 彈簧屬性


我們可以將值或值列表填充到Spring xml配置文件中定義的Java bean。

以下部分顯示如何將數(shù)據(jù)填充到j(luò)ava.util.Properties。

Java Bean

為了展示如何使用xml配置文件來填充集合屬性,我們定義了一個(gè)具有四個(gè)集合屬性的Customer對象。

package com.hgci.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.hgci.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是一個(gè)鍵值對structrue,我們可以使用以下語法來填充數(shù)據(jù)。

...
<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.hgci.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.hgci.cnmon.Person">
    <property name="name" value="java2s1" />
    <property name="address" value="address 1" />
    <property name="age" value="28" />
  </bean>
</beans>

下面是加載和運(yùn)行配置的代碼。

package com.hgci.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
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號