1. 程式人生 > >spring 管理bean

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>
別說話,點我

執行結果: