本篇文章講解了Spring的經過內部Bean設置Bean的屬性。spring
相似內部類,內部Bean與普通的Bean關聯不一樣的是:編程
1 普通的Bean,在其餘的Bean實例引用時,都引用同一個實例。app
2 內部Bean,每次引用時都是新建立的實例。ide
鑑於上述的場景,內部Bean是一個很經常使用的編程模式。函數
下面先經過前文所述的表演者的例子,描述一下主要的類:this
package com.spring.test.setter; import com.spring.test.action1.PerformanceException; import com.spring.test.action1.Performer; public class Instrumentalist implements Performer{ private String song; private int age; private Instrument instrument; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSong() { return song; } public void setSong(String song) { this.song = song; } public Instrument getInstrument() { return instrument; } public void setInstrument(Instrument instrument) { this.instrument = instrument; } public Instrumentalist(){} public Instrumentalist(String song,int age,Instrument instrument){ this.song = song; this.age = age; this.instrument = instrument; } public void perform() throws PerformanceException { System.out.println("Instrumentalist age:"+age); System.out.print("Playing "+song+":"); instrument.play(); } }
其餘代碼,以下:spa
package com.spring.test.setter; public interface Instrument { public void play(); }
package com.spring.test.setter; public class Saxophone implements Instrument { public Saxophone(){} public void play() { System.out.println("TOOT TOOT TOOT"); } }
package com.spring.test.action1; public interface Performer { void perform() throws PerformanceException; }
若是使用 設值注入 須要設定屬性和相應的setter getter方法。code
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="kenny" class="com.spring.test.setter.Instrumentalist"> <property name="song" value="Jingle Bells" /> <property name="age" value="25" /> <property name="instrument"> <bean class="com.spring.test.setter.Saxophone"/> </property> </bean> </beans>
若是使用 構造注入 須要構造函數。orm
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="kenny-constructor" class="com.spring.test.setter.Instrumentalist"> <constructor-arg value="Happy New Year"/> <constructor-arg value="30"/> <constructor-arg> <bean class="com.spring.test.setter.Saxophone"/> </constructor-arg> </bean> </beans>
應用上下文使用方法:xml
public class test { public static void main(String[] args) throws PerformanceException { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); Instrumentalist performer = (Instrumentalist)ctx.getBean("kenny"); performer.perform(); Instrumentalist performer2 = (Instrumentalist)ctx.getBean("kenny-constructor"); performer2.perform(); } }