Spring 构造器注入的多种方式

Spring 构造器注入的多种方式

<?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">

	<!--<start id="duke_bean" /> -->
	<bean id="duke" class="com.springinaction.springidol.Juggler">
		<constructor-arg name="name" value="haha" />
		<constructor-arg name="beanBags" value="15" />
		<constructor-arg name="piano" ref="piano" />

	</bean>
	<!-- 	用参数的顺序注入
	<bean id="duke" class="com.springinaction.springidol.Juggler">
		<constructor-arg index="1" value="haha" />
		<constructor-arg index="0" value="15" />
		<constructor-arg index="2" ref="piano" />

	</bean> -->
	<!-- 	用参数的类型注入
	<bean id="duke" class="com.springinaction.springidol.Juggler">
		<constructor-arg type="xx" value="haha" />
		<constructor-arg type="xx" value="15" />
		<constructor-arg type="xx" ref="piano" />

	</bean> -->
	<!-- 直接用value不过要注意的是必须按照参数的顺序
	<bean id="duke" class="com.springinaction.springidol.Juggler">
		<constructor-arg  value="haha" />
		<constructor-arg  value="15" />
		<constructor-arg  ref="piano" />

	</bean> -->
	<bean id="piano" class="com.springinaction.springidol.Piano">
	</bean>

</beans>

    

package com.springinaction.springidol;

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

public class Juggler implements Performer {
	private Integer beanBags = 3;
	private String name = "nihao";
	private Piano piano;

	public Juggler() {
	}

	public Juggler(int beanBags) {
		this.beanBags = beanBags;
	}

	public Juggler(int beanBags, String name, Piano piano) {
		this.beanBags = beanBags;
		this.name = name;
		this.piano = piano;
	}

	public void perform() throws PerformanceException {
		System.out.println("JUGGLING " + beanBags + " BEANBAGS" + name);
		piano.play();
	}

	public static void main(String args[]) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"com/springinaction/springidol/springidol-context-2.xml");
		Performer per = (Performer) ctx.getBean("duke");
		per.perform();
		
	}
}


你可能感兴趣的:(Spring 构造器注入的多种方式)