首先目录结构如下:
1. User.java
- package cn.sxt.vo;
- import java.util.Date;
- public class User {
- private String name;
- private int age;
- private Date birthday;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- @Override
- public String toString() {
- return "User [name=" + name + ", age=" + age + ", birthday=" + birthday + "]";
- }
- }
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);
- }
- }
来源: http://www.bubuko.com/infodetail-3134597.html