第3关:Bean 的构造函数注入

题解代码:

1.Student.java

package step3;
public class Student {
	private String name;
	private int age;
	private double score;
    
    /******  Begin  ******/
	Student(String name,int age,double score){
		this.name=name;
		this.age=age;
		this.score=score;
	}
	/******  End  ******/
    
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", score=" + score
				+ "]";
	}
}

2.Teacher.java

package step3;
public class Teacher {
	private String name;
	private String grade;//学生年级
	private Student student;
	
    /******  Begin  ******/
	Teacher(String name,String grade,Student student){
		this.name=name;
		this.grade=grade;
		this.student=student;
	}
    
    /******  End  ******/

	@Override
	public String toString() {
		return "Teacher [name=" + name + ", grade=" + grade + ", student="
				+ student + "]";
	}
}

3.applicationContext.java

<?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  -->
	<bean id="teacher" class="step3.Teacher">
		<constructor-arg value="张老师"></constructor-arg>
		<constructor-arg value="C366"></constructor-arg>
		<constructor-arg ref="student"></constructor-arg>
	</bean>
	<bean id="student" class="step3.Student">
		<constructor-arg value="小花"></constructor-arg>
		<constructor-arg value="18"></constructor-arg>
		<constructor-arg value="89.0"></constructor-arg>
	</bean>
	<!--结束配置  -->

</beans>

4.Test.java

package step3;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
	public static void main(String[] args) {
        
		//使用ApplicationContext容器获取对象
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext3.xml");
		Teacher t = app.getBean("teacher",Teacher.class);
        //打印对象
        System.out.println(t.toString());
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

村头卖假发的小郑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值