示例代码:http://download.csdn.net/detail/u010476739/9922323
在xml中配置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.xsd"> <!-- <bean name="dog" class="bean.Dog"></bean> --> <!-- <bean name="dogc" class="bean.Dog"> <constructor-arg value="lucy" /> </bean> --> <bean name="dogl" class="bean.Dog"> <constructor-arg> <list> <value>lucy</value> <value>tom</value> </list> </constructor-arg> </bean> <bean id="actor" class="bean.Actor"> <constructor-arg ref="dogl"></constructor-arg> </bean> <bean id="stage" class="bean.Stage" factory-method="getInstance"> </bean> <bean id="person" class="bean.Person" scope="prototype"> </bean> </beans>
应用中获取bean
package springxmldemo; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import bean.Actor; import bean.Dog; import bean.Person; import bean.Stage; public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // Dog dog=(Dog) context.getBean("dog"); // Dog dog=(Dog) context.getBean("dogc"); /* * Dog dog=(Dog) context.getBean("dogl"); * System.out.println(dog.show()); */ /* * Actor actor=(Actor) context.getBean("actor"); * System.out.println(actor.dog.show()); */ /* * Stage stage=(Stage) context.getBean("stage"); * System.out.println(stage.show()); */ Person person = (Person) context.getBean("person"); person.incre(); System.out.println(person.count); person = (Person) context.getBean("person"); person.incre(); System.out.println(person.count); } }
bean定义:
Dog
package bean; import java.util.List; public class Dog { /*public Dog(){ }*/ public String show(){ if(name!=null&&name!=""){ return "i'm a dog named "+name; } if(names!=null){ String res="i'm a dog named "; for(int i=0;i<names.size();i++){ res+=names.get(i)+","; } return res; } return "i'm a dog"; } private String name; public Dog(String name){ this.name=name; } private List<String> names; public Dog(List<String> names){ this.names=names; } }
Person
package bean; public class Person { public int count=0; public void incre(){ this.count++; } }
Stage
package bean; public class Stage { private Stage() { } public String show(){ return "i'm stage"; } private static class F{ static Stage sta= new Stage(); } public static Stage getInstance(){ return F.sta; } }
Actor
package bean; public class Actor { public Dog dog; public Actor(Dog dog) { this.dog = dog; } }