天天看點

Spring中注入基本類型

helloworld.java

package com.xy.hello;

import java.util.list;

import java.util.map;

import java.util.properties;

import java.util.set;

/**

 * 該方法spring容器通過setter方法注入

 * @author xy

 *

 */

public class helloworld

{

 public helloworld()

 {

  super();

 }

 private string name;

 private set<string> sets;

 private list<string> lst;

 private map<string, string> map;

 private properties pros;

 public void di()

  system.out.println("-----name------");

  system.out.println("hello " + name);

  system.out.println("-----sets------");

  for (string s : sets)

  {

   system.out.println(s);

  }

  system.out.println("-----lst------");

  for (string s : lst)

  system.out.println("-----map------");

  for (string key : map.keyset())

   system.out.println(key + "..." + map.get(key));

  system.out.println("-----pro------");

  for (object key : pros.keyset())

   system.out.println(key + "..." + pros.getproperty((string) key));

 /***************************** getter和setter **************************************/

 public string getname()

  return name;

 public void setname(string name)

  this.name = name;

 public set<string> getsets()

  return sets;

 public void setsets(set<string> sets)

  this.sets = sets;

 public list<string> getlst()

  return lst;

 public void setlst(list<string> lst)

  this.lst = lst;

 public map<string, string> getmap()

  return map;

 public void setmap(map<string, string> map)

  this.map = map;

 public properties getpros()

  return pros;

 public void setpros(properties pros)

  this.pros = pros;

}

beans.xml

<?xml version="1.0" encoding="utf-8"?>

<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="xyhello" class="com.xy.hello.helloworld">

  <property name="name">

   <value>xy</value>

  </property>

  <property name="sets">

   <set>

    <value>set1</value>

    <value>set2</value>

    <value>set3</value>

   </set>

  <property name="lst">

   <list>

    <value>lst1</value>

    <value>lst2</value>

    <value>lst3</value>

   </list>

  <property name="map">

   <map>

    <entry key="mk1" value="mv1"></entry>

    <entry key="mk2" value="mv2"></entry>

    <entry key="mk3" value="mv3"></entry>

   </map>

  <property name="pros">

   <props>

    <prop key="pk1">pv1</prop>

    <prop key="pk2">pv2</prop>

    <prop key="pk3">pv3</prop>

   </props>

 </bean>

</beans>

testjunit.java

public class testjunit

 @test

 public void test()

  // 啟動spring容器

  applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");

  // 容器中擷取類的執行個體

  helloworld hello = (helloworld) context.getbean("xyhello");

  // 調用方法

  hello.di();