【Spring實戰】—— 5 設值注入

本篇主要講解了Spring的最經常使用的功能——依賴注入。spring

注入的方式,是使用Getter Setter注入,平時大多的編程也都是使用這種方法。編程

  舉個簡單的例子,仍是表演者。this

  表演者有本身的屬性,年齡或者表演的歌曲等等。還須要一些複雜的屬性,好比樂器,每一種樂器會發出不一樣的聲音。spa

  下面看一下表演者Performercode

package com.spring.test.action1; public interface Performer { void perform() throws PerformanceException; }

  咱們本身定義一個鋼琴演奏者,該表演者有年齡和歌曲,還有額外的一種樂器屬性。orm

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 void perform() throws PerformanceException { System.out.println("Instrumentalist age:"+age); System.out.print("Playing "+song+":"); instrument.play(); } }

  樂器的構造以下,依然使用接口方式:xml

package com.spring.test.setter; public interface Instrument { public void play(); }

  薩克斯實現該樂器接口blog

package com.spring.test.setter; public class Saxophone implements Instrument { public Saxophone(){} public void play() { System.out.println("TOOT TOOT TOOT"); } }

  以上就是基本的類的構造了。接口

  下面看一下Spring的配置文件:get

<?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="sax" class="com.spring.test.setter.Saxophone"/>
     <bean id="kenny" class="com.spring.test.setter.Instrumentalist">
         <property name="song" value="Jingle Bells" />
         <property name="age" value="25" />
         <property name="instrument" ref="sax" />
     </bean>
</beans>

  在配置文件中,能夠發現,設值注入時,使用name來指定注入哪一個屬性

  name的命名方式依據變量名稱。

  1 首字母不區分大小寫,其餘部分與變量名稱相同。

  2 注入的屬性類型,能夠是String , int , double , float等,當屬性是String或int時,能夠根據變量的類型自動轉換。

  3 注入的是一個bean,則直接使用ref連接到另外一個bean便可。

  下面是應用上下文的代碼:

package com.spring.test.setter; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.test.action1.PerformanceException; 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 age:25 Playing Jingle Bells:TOOT TOOT TOOT
相關文章
相關標籤/搜索