spring学习笔记3-Spring自动装配-由构造函数自动装配

Spring自动装配-由构造函数自动装配

由构造函数自动装配

这种模式与 byType 非常相似,但它应用于构造器参数。Spring 容器看作 beans,在 XML 配置文件中 beans 的 autowire 属性设置为 constructor。然后,它尝试把它的构造函数的参数与配置文件中 beans 名称中的一个进行匹配和连线。如果找到匹配项,它会注入这些 bean,否则,它会抛出异常。

实例:

  1. 在eclipse中新建一个名为autowire的Java工程
  2. 带入spring所需要的包
  3. 在src下新建一个名为autoTest02的包,在包下新建MainTest.java,Tstudent02.java,和Tteacher02.java三个class文件
  4. 在src下创建Beans.xml文件

下面是MainTest.java的内容:

package autowireTest02;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
		Tstudent02 student = (Tstudent02)context.getBean("Tstudent02");
		System.out.println(student);
	}
}

下面是Tstudent.java的内容:

package autowireTest02;

public class Tstudent02 {
	private String name;
	private Tteacher02 teacher02;
	public Tstudent02(String name,Tteacher02 teacher02) {
		this.name=name;
		this.teacher02=teacher02;
	}
	
	public String toString() {
		return "my name is "+name+",and my teacher's name is "+teacher02.getName();
	}
}

下面是Tteacher02.java的内容:

package autowireTest02;

public class Tteacher02 {
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

下面是Beans.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<bean id="Tstudent01" class="autowireTest01.Tstudent" autowire="byName">
		<property name="name" value="zs"></property>
	</bean>

	<bean id="teacher" class="autowireTest01.Tteacher">
		<property name="name" value="ls"></property>
	</bean>
	
	<bean id="Tstudent02" class="autowireTest02.Tstudent02" autowire="constructor">
		<constructor-arg value="zs"></constructor-arg>
	</bean>
	
	<bean id="teacher02" class="autowireTest02.Tteacher02">
		<property name="name" value="ls"></property>
	</bean>
	
</beans>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值