别的不多说,咱们先上代码
1> object.xml 的文件内容
<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd"> <object id="car1" type="Spring_constructor.Car, Spring_constructor" > <constructor-arg value="BMW" /> <constructor-arg value="300000"/> </object> </objects>
2> main函数
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 // 1.引用spring.net 库 6 using Spring.Context.Support; 7 using Spring.Context; 8 9 namespace Spring_constructor 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 #region 构造器注入 16 ///* 17 string path = System.AppDomain.CurrentDomain.BaseDirectory + "object.xml"; 18 19 // 2.构造IOC 容器 20 IApplicationContext ctx = new XmlApplicationContext(path); 21 22 // 3.在IOC容器中获取实例 23 Car car = ctx.GetObject("car1") as Car; 24 25 26 // 4.调用hello方法 27 //he.Hello(); 28 Console.WriteLine(car.name); 29 Console.WriteLine(car.price); 30 //Console.WriteLine(car.maxspeed); 31 // * */ 32 #endregion 33 Console.ReadKey(); 34 } 35 } 36 37 class Car 38 { 39 public string name { get; set; } 40 public int price { get; set; } 41 public double size { get; set; } 42 public int maxspeed { set; get; } 43 public string place { get; set; } 44 45 public Car(string name,int price) 46 { 47 this.name = name; 48 this.price = price; 49 } 50 } 51 }
3> 说明
通过构造器注入时,我们要用到 <constructor-arg>节点,其中我们可以设置它的属性,比如 value、 type、index等。
当我们的构造函数重载时,如下代码:
1 public Car(string name, int price,int maxspeed) 2 { 3 this.name = name; 4 this.price = price; 5 this.maxspeed = maxspeed; 6 }
对应的配置文件就可以更改为:
<object id="car1" type="Spring_constructor.Car, Spring_constructor" > <constructor-arg value="BMW" type="string" index="0" /> <constructor-arg value="300000" type="int" index="1"/> <constructor-arg value="200" type="int" index="2"/> </object>
通过type与index属性来确定我们要传入的参数具体是第几个参数,类型是什么,index初始值为0.
当我们配置的值有特殊字符时, 我们可以通过<![CDATA[]]> 来配置,如下代码:
<constructor-arg> <value><![CDATA["BMW"]]></value> </constructor-arg>