2.开发Spring IOC程序

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了对象,并且给对象赋了值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值