Spring设值注入

1、class Student

package com.di01;

public class Student {
private String name;
private int age;
private School school;

public void setName(String name) {
	System.out.println("执行setName");
	this.name = name;
}
public void setAge(int age) {
	System.out.println("执行setAge");
	this.age = age;
}

public void setSchool(School school) {
	this.school = school;
}

@Override
public String toString() {
	return "Student [name=" + name + ", age=" + age + ", school=" + school + "]";
}

}

2、class MyTest

package com.di01;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

public class MyTest {

@Test
public void test01() {
	ApplicationContext ac = new ClassPathXmlApplicationContext("com/di01/applicationContext.xml");
	Student student = (Student) ac.getBean("myStudent");
	System.out.println(student);
}

}

3、applicationContext.xml

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

<!-- 注册School -->
<bean id="mySchool" class="com.di01.School">
	<property name="name" value="清华大学"/>
</bean>

<!-- 注册Student -->
<bean id="myStudent" class="com.di01.Student">
	<property name="name" value="张三"/>
	<property name="age" value="22"/>
	<property name="school" ref="mySchool"/>
</bean>
发布了47 篇原创文章 · 获赞 1 · 访问量 384

猜你喜欢

转载自blog.csdn.net/weixin_43925059/article/details/104894839