spring 构造器流入
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!