我們可以通過(guò)構(gòu)造函數(shù)注入依賴(lài)項(xiàng)。 <bean>的 <constructor-arg>子元素用于構(gòu)造函數(shù)注入。在這里,我們要注入
原始和基于字符串的值 從屬對(duì)象(包含對(duì)象) 集合值等
讓我們看一下注入原始值和基于字符串的簡(jiǎn)單示例價(jià)值觀。我們?cè)谶@里創(chuàng)建了三個(gè)文件:
Employee.java applicationContext.xml Test.java
Employee.java
這是一個(gè)簡(jiǎn)單的類(lèi),包含兩個(gè)字段id和name。此類(lèi)中有四個(gè)構(gòu)造函數(shù)和一個(gè)方法。
package com.nhooo; public class Employee { private int id; private String name; public Employee() {System.out.println("def cons");} public Employee(int id) {this.id = id;} public Employee(String name) { this.name = name;} public Employee(int id, String name) { this.id = id; this.name = name; } void show(){ System.out.println(id+" "+name); } }
applicationContext.xml
我們通過(guò)此文件將信息提供給Bean。 constructor-arg元素調(diào)用構(gòu)造函數(shù)。在這種情況下,將調(diào)用int類(lèi)型的參數(shù)化構(gòu)造函數(shù)。 Constructor-arg元素的value屬性將分配指定的值。 type屬性指定將調(diào)用int參數(shù)構(gòu)造函數(shù)。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="e" class="com.nhooo.Employee"> <constructor-arg value="10" type="int"></constructor-arg> </bean> </beans>
Test.java
此類(lèi)從applicationContext.xml文件獲取Bean并調(diào)用show方法。
package com.nhooo; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.*; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); Employee s=(Employee)factory.getBean("e"); s.show(); } }
輸出: 10空
如果您未在構(gòu)造函數(shù)arg元素中指定type屬性,則默認(rèn)情況下將調(diào)用字符串類(lèi)型構(gòu)造函數(shù)。
.... <bean id="e" class="com.nhooo.Employee"> <constructor-arg value="10"></constructor-arg> </bean> ....
如果如上所述更改bean元素,則將調(diào)用字符串參數(shù)構(gòu)造函數(shù),并且輸出將為0 10。
輸出: 0 10
您還可以按如下所示傳遞字符串文字:
.... <bean id="e" class="com.nhooo.Employee"> <constructor-arg value="Sonoo"></constructor-arg> </bean> ....
輸出: 0 Sonoo
您可以按以下方式傳遞整數(shù)文字和字符串
.... <bean id="e" class="com.nhooo.Employee"> <constructor-arg value="10" type="int" ></constructor-arg> <constructor-arg value="Sonoo"></constructor-arg> </bean> ....
輸出: 10 Sonoo