使用静态工厂方法注入

package org.spring.chapter2.helloworld;

public class HelloImpl3 implements HelloApi {

	private String message;
	private int index;
	
	public HelloImpl3() {
		this.message="Hello World in Empty Constructor";
	}

	public HelloImpl3(String message,int index) {
		this.message = message;
		this.index = index;
	}

	@Override
	public void sayHello() {
		System.out.println(index+":"+message);
	}

}
package org.spring.chapter2.helloworld;

public class InJectByStaticFactory {

	public static HelloApi newInstance(String message,int index){
		return new HelloImpl3(message,index);
	}
}
<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
	     				http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/context           
     					http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<!-- 通过构造器参数索引方式依赖注入 -->  
	<bean id="byIndex" class="org.spring.chapter2.helloworld.InJectByStaticFactory" factory-method="newInstance">
	   <constructor-arg index="0" value="Hello Spring By Index" />
	   <constructor-arg index="1" value="1"></constructor-arg>
	</bean>
	<!-- 通过构造器参数类型方式依赖注入 -->  
	<bean id="byType" class="org.spring.chapter2.helloworld.InJectByStaticFactory" factory-method="newInstance">
	   <constructor-arg type="java.lang.String" value="Hello Spring By Type" />
	   <constructor-arg type="int" value="2" />
	</bean>
	
	<!-- 通过构造器参数名称方式依赖注入 -->  
	<bean id="byName" class="org.spring.chapter2.helloworld.InJectByStaticFactory" factory-method="newInstance">
	    <constructor-arg name="message" value="Hello Spring By Name" />
	    <constructor-arg name="index" value="3"/>
	</bean>
	
</beans>
@Test
	public void testStaticConstructInject(){
		ApplicationContext context = new ClassPathXmlApplicationContext("org/spring/chapter2/helloworld/helloworld5.xml");
		
		//1:按照参数索引依赖注入的Bean
		HelloApi byIndex = context.getBean("byIndex",HelloApi.class);
		byIndex.sayHello();
		//2:按照参数类型依赖注入的Bean
		HelloApi byType = context.getBean("byType",HelloApi.class);
		byType.sayHello();
		//3:根据参数名称依赖注入的Bean
		HelloApi byName = context.getBean("byName",HelloApi.class);
		byName.sayHello();
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值