spring 构造器注入

1、创建HelloApi接口:

package com.spring.service;
public interface HelloApi {
    public void sayHello();
}

 2、创建HelloApiImpl1 带构造器实现HelloApi接口类:

package com.spring.service.impl;
import com.spring.service.HelloApi;
public class HelloApiImpl1 implements HelloApi {
	private String message;
	private int index;
	//@java.beans.ConstructorProperties({"message","index"})
	public HelloApiImpl1(String message,int index){
		this.message=message;
		this.index=index;
	}
	@Override
	public void sayHello() {
		System.out.println(index+": "+message);
	}
}

3、创建Bean配置文件:spring-zhuru.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">
	<!-- 通过构造器参数索引方式依赖注入 -->
	<bean id="byIndex" class="com.spring.service.impl.HelloApiImpl1">
		<!-- index表示索引,从0开始,第一个参数索引为0,value 来指定注入的常量值。 -->
		<constructor-arg index="0" value="Hello World!" />
		<constructor-arg index="1" value="1" />
	</bean>
	<!-- 通过构造器参数类型方式依赖注入 :type表示需要匹配的参数类型,可以是基本类型也可以是其他类型,value表示指定注入的常量值 -->
	<bean id="byType" class="com.spring.service.impl.HelloApiImpl1">
		<constructor-arg type="java.lang.String" value="Hello World!" />
		<constructor-arg type="int" value="2" />
	</bean>
	<!-- 根据参数名进行注入 ,name表示需要匹配的参数名字,value来指定注入的常量值 -->
	<bean id="byName" class="com.spring.service.impl.HelloApiImpl1">
		<constructor-arg name="message" value="Hello World!" />
		<constructor-arg name="index" value="3" />
	</bean>
</beans>

 4、创建ConstructorDependencyInjectTest类测试:

package com.spring.test;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.service.HelloApi;
public class ConstructorDependencyInjectTest {
	@Test
	public void testDI(){
		BeanFactory beanFactory=new ClassPathXmlApplicationContext("spring-zhuru.xml");
		//获取根据参数索引依赖注入的Bean
		HelloApi byIndex=beanFactory.getBean("byIndex", HelloApi.class);
		byIndex.sayHello();
		//获取根据参数类型注入的Bean
		HelloApi byType=beanFactory.getBean("byType", HelloApi.class);
		byType.sayHello();
		//获取根据参数名字依赖注入的Bean
		HelloApi byName=beanFactory.getBean("byName", HelloApi.class);
		byName.sayHello();	
	}
}

 5输出结果:

1: Hello World!
2: Hello World!
3: Hello World!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值