一、建立项目

二、添加Spring的库文件

三、添加Spring配置文件

四、编写Bean类

代码:

public class User {

private int id;

private String userName;

private String passWord;

public User() {

super();

// TODO Auto-generated constructor stub

}

public User(int id, String userName, String passWord) {

super();

this.id = id;

this.userName = userName;

this.passWord = passWord;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getPassWord() {

return passWord;

}

public void setPassWord(String passWord) {

this.passWord = passWord;

}

@Override

public String toString() {

return "User [id=" + id + ", passWord=" + passWord + ", userName="

+ userName + "]";

}

}

五、编写配置文件

代码:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="user" class="com.vo.User">

<property name="passWord">

<value>123</value>

</property>

<property name="userName">

<value>admin</value>

</property>

<property name="id">

<value>1</value>

</property>

</bean>

</beans>

六、测试

代码:

public class Test {

public static void main(String[] args) {

BeanFactory beanFactory = new ClassPathXmlApplicationContext("applicationContext.xml");

User user = (User)beanFactory.getBean("user");

System.out.println(user);

}

}