1.Student.java
package nuc.hzb.entity;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Student {
private int no;
private String name;
private int age;
public Student() {}
public Student(int no, String name, int age) {
super();
this.no = no;
this.name = name;
this.age = age;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
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;
}
@Override
public String toString() {
return "Student [no=" + no + ", name=" + name + ", age=" + age + "]";
}
}
2.applicationContext.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">
<!--该文件中产生的所有对象,被Spring放入了一个称之为Spring IOC容器的地方 -->
<!-- Spring IOC容器
1.创建对象
2.给对象的属性赋值
-->
<bean id="student" class="nuc.hzb.entity.Student">
<property name="no" value="16"></property>
<property name="name" value="黄朝博"></property>
<property name="age" value="20"></property>
</bean>
</beans>
3.StudentTest.java
package nuc.hzb.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import nuc.hzb.entity.Student;
public class StudentTest {
private static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
public static void CreatebyObject() {
Student student = new Student();
student.setNo(1);
student.setName("hzb");
student.setAge(18);
System.out.println(student);
}
public static void SpringIOC() {
// Student studentObject = (Student)context.getBean("student");
// 其实不需要强制转化
Object bean = context.getBean("student");
System.out.println(bean);
}
public static void learnCourseWithFactory() {
Student student = new Student();
student.learn("javaCourse");
student.learn("htmlCourse");
}
public static void main(String[] args) {
CreatebyObject();
SpringIOC();
learnCourseWithFactory();
}
}
4.说明
ApplicationContext conext = new ClassPathXmlApplicationContext(“applicationContext.xml”);
执行从Spring IOC容器中获取一个id为student的对象
Student student = (Student)conext.getBean(“student”);
可以发现,Spring IOC容器帮我们new了对象,并且给对象赋了值