Spring教程 - Spring構(gòu)造函數(shù)注入

2018-01-09 19:06 更新

Spring教程 - Spring構(gòu)造函數(shù)注入


我們可以通過構(gòu)造函數(shù)注入依賴。

構(gòu)造函數(shù)依賴注入發(fā)生在Java Bean的依賴關(guān)系在其構(gòu)造函數(shù)中提供給它。

Java Bean聲明一個(gè)構(gòu)造函數(shù)或一組構(gòu)造函數(shù),從參數(shù)中獲取其依賴性,以及IoC容器在實(shí)例化時(shí)將依賴性傳遞給Java Bean。

例子

假設(shè)我們定義了以下接口和Java bean。

package com.www.o2fo.common;
public interface Printer
{
  public void print();
}

之后,我們將創(chuàng)建CSV打印機(jī),將輸出CSV格式的數(shù)據(jù)。CSV打印機(jī)實(shí)現(xiàn)打印機(jī)接口。

package com.www.o2fo.common;
public class CSVPrinter implements Printer
{
  public void print(){
    System.out.println("Csv Output Printer");
  }
}

然后是時(shí)間創(chuàng)建JSON打印機(jī)將輸出JSON格式的消息。JSON打印機(jī)還實(shí)現(xiàn)了打印機(jī)接口。

package com.www.o2fo.common;
public class JSONPrinter implements Printer
{
  public void print(){
    System.out.println("Json Output Printer");
  }
}

一個(gè)帶有構(gòu)造函數(shù)的助手類。

package com.www.o2fo.common;
public class OutputHelper
{
  Printer outputGenerator;
    public OutputHelper(){
  }
    public OutputHelper(Printer p){
    this.outputGenerator = p;
  }
    public void print(){
      outputGenerator.print();
    }
    
}

以下Spring bean配置文件聲明并通過使用 constructor-arg 標(biāo)記的構(gòu)造函數(shù)注入來設(shè)置依賴關(guān)系。

<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-2.5.xsd">
  <bean id="outputHelper" class="com.www.o2fo.common.OutputHelper">
    <constructor-arg>
      <bean class="com.www.o2fo.common.CSVPrinter" />
    </constructor-arg>
  </bean>
    <bean id="csvPrinter" class="com.www.o2fo.common.CSVPrinter" />
    <bean id="jsonPrinter" class="com.www.o2fo.common.JSONPrinter" />
</beans>


加載配置和運(yùn)行

下面的代碼展示了如何加載Spring配置文件并運(yùn)行應(yīng)用程序。

package com.www.o2fo.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext(
        "SpringBeans.xml");
    OutputHelper output = (OutputHelper)context.getBean("outputHelper");
              output.print();
  }
}

輸出


Download Java2s_Spring_Constructor_Injection.zip


構(gòu)造函數(shù)注入類型模糊

以下Employee類有兩個(gè)構(gòu)造函數(shù)方法。它們都接受具有不同數(shù)據(jù)類型的3個(gè)參數(shù)。

package com.www.o2fo.common;
public class Employee 
{
  private String name;
  private String address;
  private int age;
  public Employee(String name, String address, int age) {
    this.name = name;
    this.address = address;
    this.age = age;
  }
  public Employee(String name, int age, String address) {
    this.name = name;
    this.age = age;
    this.address = address;
  }
  public String toString(){
    return " name : " +name + " address : " + address + " age : " + age;
  }
}

第一個(gè)具有以下參數(shù)

public Employee(String name, String address, int age)

第二個(gè)定義如下。

public Employee(String name, int age, String address)

年齡和地址切換位置。

當(dāng)在Spring配置中創(chuàng)建Employee對(duì)象時(shí),我們使用xml文件 constructor-arg 標(biāo)記來為構(gòu)造函數(shù)中的參數(shù)提供值。

在下面的Spring bean配置文件中,我們傳遞了“java2s"的name,“1000"表示地址,“28"表示年齡。

<myPreCode>
<beans ...
  <bean id="myEmployee" class="com.www.o2fo.common.Employee">
    <constructor-arg>
      <value>java2s</value>
    </constructor-arg>
    <constructor-arg>
      <value>1000</value>
    </constructor-arg>
    <constructor-arg>
      <value>28</value>
    </constructor-arg>
        </bean>
</beans>

這里是運(yùn)行我們上面設(shè)置的配置的代碼。

package com.www.o2fo.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App 
{
    public static void main( String[] args )
    {
      ApplicationContext context = 
        new ClassPathXmlApplicationContext(new String[] {"Spring-Employee.xml"});
      Employee cust = (Employee)context.getBean("myEmployee");
      System.out.println(cust);
    }
}

輸出

從結(jié)果字符串,我們可以看到第二個(gè)構(gòu)造函數(shù)而不是第一個(gè)構(gòu)造函數(shù)。

Spring將參數(shù)“1000"轉(zhuǎn)換為int,然后調(diào)用接受第二個(gè)構(gòu)造函數(shù),即使我們在值中作為String類型傳遞。

如果Spring找不到正確的構(gòu)造函數(shù)使用,它會(huì)提示以下錯(cuò)誤信息

constructor arguments specified but no matching constructor 
found in bean "myEmployee" (hint: specify index and/or 
type arguments for simple parameters to avoid type ambiguities)

為了在構(gòu)造函數(shù)中匹配參數(shù)類型,我們可以通過type屬性指定構(gòu)造函數(shù)的數(shù)據(jù)類型在 constructor-arg 標(biāo)記中。

<beans ...
  <bean id="myEmployee" class="com.www.o2fo.common.Employee">
    <constructor-arg type="java.lang.String">
      <value>java2s</value>
    </constructor-arg>
    <constructor-arg type="java.lang.String">
      <value>1000</value>
    </constructor-arg>
    <constructor-arg type="int">
      <value>28</value>
    </constructor-arg>
  </bean>
</beans>

再次運(yùn)行。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)