第一个Spring
Student(学生) bean
package com.my.bean; import java.io.Serializable; public class Student implements Serializable{ private static final long serialVersionUID = 1L; private String name; private MyClass myClass; public String getName() { return name; } public void setName(String name) { this.name = name; } public MyClass getMyClass() { return myClass; } public void setMyClass(MyClass myClass) { this.myClass = myClass; } }
Class(班级) bean
package com.my.bean; import java.io.Serializable; public class MyClass implements Serializable{ private static final long serialVersionUID = 1L; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
需要导入的jar包
beans配置文件
<?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"> <bean id="stu" class="com.my.bean.Student"> <property name="name" value="小明"/> <property name="myClass" ref="cls"/> </bean> <bean id="cls" class="com.my.bean.MyClass"> <property name="name" value="班级一"/> </bean> </beans>
获取已经配置的Student类
package com.my.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.my.bean.Student; public class Test { /** * @param args */ public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //获取已经配置的Stu Student stu = context.getBean("stu",Student.class); System.err.println(stu.getName()); } }