【Spring實戰】—— 2 構造注入

weixin_33831673發表於2015-01-24

本文講解了構造注入以及spring的基本使用方式,通過一個雜技演員的例子,講述了依賴注入屬性或者物件的使用方法。

  如果想要使用spring來實現依賴注入,需要幾個重要的步驟:

  1 定義主要的類和需要分離的屬性。這裡主要的類,是指程式的主要物件,在例子中是Juggler雜技員。而想要分離構造的屬性,是它手中的袋子的數目beanBags。

  2 配置bean.xml。通過配置檔案,確定主要的類和屬性之間的關係,以及實現類。

  3 通過應用上下文,獲取bean,並進行使用。

注入屬性

  例項程式碼:

  1 表演者介面:Performer.java

package com.spring.test.action1;

public interface Performer {
    void perform() throws PerformanceException;
}

  2 雜技員:Juggler,繼承了表演者介面

package com.spring.test.action1;

public class Juggler implements Performer{
    private int beanBags = 3;
    
    public Juggler(){
        
    }
    
    public Juggler(int beanBags){
        this.beanBags = beanBags;
    }
    
    public void perform() throws PerformanceException {
        System.out.println("Juggler "+beanBags+" beanBags");
    }

}

  3 Spring配置檔案:bean.xml

<?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="duke" class="com.spring.test.action1.Juggler">
         <constructor-arg value="15"/>
     </bean>
</beans>

  4 應用上下文獲取指定的bean

package com.spring.test.action1;

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

public class test {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
        Performer performer = (Performer)ctx.getBean("duke");
        try {
            performer.perform();
        } catch (PerformanceException e) {
            e.printStackTrace();
        }
    }
}

  執行結果如下:

Juggler 15 beanBags

 

注入物件

  1 例如,上面的雜技演員不僅僅會仍袋子,還會表演詩歌,那麼詩歌這個物件就需要注入到表演者的建構函式中,可以如下表示會朗誦詩歌的雜技演員:PoeticJuggler

package com.spring.test.action1;

public class PoeticJuggler extends Juggler{
    private Poem poem;
    
    public PoeticJuggler(Poem poem){
        super();
        this.poem = poem;
    }
    
    public PoeticJuggler(int beanBags,Poem poem){
        super(beanBags);
        this.poem = poem;
    }
    
    public void perform() throws PerformanceException {
        super.perform();
        System.out.println("While reciting...");
        poem.recite();
    }

}

  2 詩歌物件:Sonnet29

package com.spring.test.action1;

public class Sonnet29 implements Poem{
    private static String lines = "嘛咪嘛咪哄";
    
    public Sonnet29() {
        
    }
    
    public void recite() {
        System.out.println(lines);
    }

}

  3 Bean.xml配置檔案如下

<?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="duke" class="com.spring.test.action1.Juggler">
         <constructor-arg value="15"/>
     </bean>
     <bean id="sonnet29" class="com.spring.test.action1.Sonnet29"/>
     <bean id="poeticDuke" class="com.spring.test.action1.PoeticJuggler">
         <constructor-arg value="15"/>
         <constructor-arg ref="sonnet29"/>
     </bean>
</beans>

  4 主要的執行程式碼,通過應用上下文獲取制定的bean

package com.spring.test.action1;

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

public class test {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
//        Performer performer = (Performer)ctx.getBean("duke");
        Performer performer1 = (Performer)ctx.getBean("poeticDuke");
        try {
//            performer.perform();
            performer1.perform();
        } catch (PerformanceException e) {
            e.printStackTrace();
        }
    }
}

  5 執行結果如下

一月 24, 2015 4:40:46 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
資訊: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@35bf8de1: startup date [Sat Jan 24 16:40:46 CST 2015]; root of context hierarchy
一月 24, 2015 4:40:46 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
資訊: Loading XML bean definitions from class path resource [bean.xml]
一月 24, 2015 4:40:46 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
資訊: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3401a0ad: defining beans [duke,sonnet29,poeticDuke]; root of factory hierarchy
Juggler 15 beanBags
While reciting...
嘛咪嘛咪哄

 

相關文章