First, the directory structure is as follows:
1. User.java
1 package cn.sxt.vo; 2 3 import java.util.Date; 4 5 public class User { 6 7 private String name; 8 private int age; 9 private Date birthday; 10 public String getName() { 11 return name; 12 } 13 public void setName(String name) { 14 this.name = name; 15 } 16 public int getAge() { 17 return age; 18 } 19 public void setAge(int age) { 20 this.age = age; 21 } 22 public Date getBirthday() { 23 return birthday; 24 } 25 public void setBirthday(Date birthday) { 26 this.birthday = birthday; 27 } 28 @Override 29 public String toString() { 30 return "User [name=" + name + ", age=" + age + ", birthday=" + birthday + "]"; 31 } 32 }
2. beans.xml
<? XML Version = "1.0" encoding = "UTF-. 8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: the 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 "> <-! import for importing major role in other configuration information is developed using teamwork -> < import Resource = " context.xml " /> </ Beans>
3. context.xml
<? XML Version = "1.0" encoding = "UTF-. 8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: the xsi = "http://www.w3.org / 2001 / the XMLSchema-instance " the xsi: the schemaLocation =" http://www.springframework.org/schema/beans HTTP: // www.springframework.org/schema/beans/spring-beans.xsd "> < description > description information </ Description> <-! the bean represents java object id is the identifier of the object only in the container . You may be acquired by the object identifier from the container . If no name id configured, then the name will serve as the identifier of the object , if the configuration of the id, the id is an alias . Simultaneously may be provided a plurality of aliases, a separator (a comma, a space between the plurality of aliases, Where the fully qualified class name = name + packet class name; -> < the bean ID = "User" name = "U1, U2 U3; U4" class = "cn.sxt.vo.User"> <-! Property represents a property of the class, set the need to provide a method to set the value to an object . name is a set method after removing the set value of the set value of the attribute, value and the basic data types may be provided to the String attribute . If the value is a need to use an object reference ref attribute -> < Property name = "name" value = "Joe Smith crazy" /> <Property name = "Age" value = "22 is" /> </ the bean> <! <alias name="user" alias="u5"/> </beans>
4. SpringTest.java
package cn.sxt.spring; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.sxt.vo.User; public class SpringTest { @Test public void testHello(){ ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml"); User u=(User)ac.getBean("u4"); System.out.println(u); } }