【Spring實戰】—— 8 自動裝配

本篇介紹一下自動裝配的知識,Spring爲了簡化配置文件的編寫。採用自動裝配方式,自動的裝載須要的bean。spring

  自動裝配 有如下幾種方式:ide

  1 byName 經過id的名字與屬性的名字進行判斷,要保證Bean實例中屬性名字與該裝配的id名字相同。測試

  2 byType 經過類型肯定裝配的bean,可是當存在多個類型符合的bean時,會報錯。this

  3 contructor 在構造注入時,使用該裝配方式,效果如同byType。spa

  4 autodetect 自動裝配,這個測試了,3.0.5版本不可用了,不知道是否是被移除了。code

 

  下面簡單的看下,自動裝配的所需代碼:orm

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(); } }
View Code
public interface Instrument { public void play(); }
View Code
public class Saxophone implements Instrument { public Saxophone(){} public void play() { System.out.println("TOOT TOOT TOOT"); } }
View Code
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(); } }
View Code

  採用byName方式的配置文件以下:

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

  採用byType的配置文件以下:

<?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="test2" class="com.spring.test.setter.Saxophone"/>
    <bean id="test1" class="com.spring.test.setter.Saxophone" primary="true"/> <!-- 默認是false -->
    <bean id="kenny" class="com.spring.test.setter.Instrumentalist" autowire="byType">
         <property name="song" value="Jingle Bells" />
         <property name="age" value="25" />
     </bean>
</beans>

  若是有多個類型匹配的bean,則能夠採用 primary 來設置主要裝配的bean,默認狀況下是falsexml

相關文章
相關標籤/搜索