spring 管理bean
目录结构:
Person.java
1 package com.wss.entity; 2 3 import com.wss.service.doHomeWork; 4 5 public class Person { 6 7 private String name; 8 private int age; 9 private doHomeWork dohomework; 10 11 public void setDoHomeWork(doHomeWork dohomework) { 12 this.dohomework = dohomework; 13 } 14 public doHomeWork getDoHomeWork() { 15 return this.dohomework; 16 } 17 public String getName() { 18 return name; 19 } 20 public void setName(String name) { 21 this.name = name; 22 } 23 public int getAge() { 24 return age; 25 } 26 public void setAge(int age) { 27 this.age = age; 28 } 29 @Override 30 public String toString() { 31 return "Person [name=" + name + ", age=" + age + ", dohomework=" + dohomework + "]"; 32 } 33 }
doHomeWork.java
1 package com.wss.service; 2 3 public class doHomeWork { 4 5 public String write() { 6 return new String("write"); 7 } 8 }
PersonTest.java
1 package com.wss.test; 2 3 import org.junit.Test; 4 import org.springframework.context.ApplicationContext; 5 import org.springframework.context.support.ClassPathXmlApplicationContext; 6 7 import com.wss.entity.Person; 8 9 public class PersonTest { 10 11 @Test 12 public void test1() { 13 ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); 14 Person person = context.getBean("person", Person.class); 15 System.out.println(person.toString()); 16 System.out.println(person.getDoHomeWork().write()); 17 } 18 }
spring-config.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 <!-- 配置person实例,其实现类是Person --> 7 <bean id="person" class="com.wss.entity.Person"> 8 <property name="name" value="wss"></property> 9 <property name="age" value="24"></property> 10 <!-- 驱动调用person的setDoHomeWork()方法,将容器中的stoneAxe作为参数传入 --> 11 <property name="doHomeWork" ref="dohomework"></property> 12 </bean> 13 <!-- 配置dohomework实例,其实现类是doHomeWork --> 14 <bean id="dohomework" class="com.wss.service.doHomeWork"></bean> 15 </beans>
运行结果:
两种注入方式: