首先目录结构如下:
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: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用于导入其他配置信息 主要的作用就是团队协作开发使用
-->
<import resource="context.xml"/>
</beans>
3. context.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.xsd">
<description>
描述信息
</description>
<!--
bean 表示java对象 id是对象的标识符,在容器中唯一。通过标识符可以从容器中获取对象。
name 如果没有配置id,那么name将作为对象的标识符,如果配置了id,那么是id的别名。
可以同时设置多个别名,多个别名之间用分隔符(逗号,空格,分号)分割
class 类所在的完全限定名=包名+类名;
-->
<bean id="user" name="u1,u2 u3;u4" class="cn.sxt.vo.User">
<!-- property 表示类的属性设置,需要为其提供set方法,以便将值设置到对象上。
name 表示set方法去掉set后的名称
value 设置属性的值,value可以将基本数据类型和String设置到属性上。
如果值是一个对象 需要使用ref属性引用
-->
<property name="name" value="张三疯"/>
<property name="age" value="22"/>
</bean>
<!-- 设置别名 通常设置一个
name表示要设置别名的对象的标识符
alias 表示 设置的别名名称
-->
<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);
}
}