Spring.net 学习IOC------通过构造器注入

时间:2023-07-03 17:22:35

别的不多说,咱们先上代码

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=""/>
</object>
</objects>

2> main函数

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// 1.引用spring.net 库
using Spring.Context.Support;
using Spring.Context; namespace Spring_constructor
{
class Program
{
static void Main(string[] args)
{
#region 构造器注入
///*
string path = System.AppDomain.CurrentDomain.BaseDirectory + "object.xml"; // 2.构造IOC 容器
IApplicationContext ctx = new XmlApplicationContext(path); // 3.在IOC容器中获取实例
Car car = ctx.GetObject("car1") as Car; // 4.调用hello方法
//he.Hello();
Console.WriteLine(car.name);
Console.WriteLine(car.price);
//Console.WriteLine(car.maxspeed);
// * */
#endregion
Console.ReadKey();
}
} class Car
{
public string name { get; set; }
public int price { get; set; }
public double size { get; set; }
public int maxspeed { set; get; }
public string place { get; set; } public Car(string name,int price)
{
this.name = name;
this.price = price;
}
}
}

3> 说明

通过构造器注入时,我们要用到 <constructor-arg>节点,其中我们可以设置它的属性,比如 value、 type、index等。

当我们的构造函数重载时,如下代码:

 public Car(string name, int price,int maxspeed)
{
this.name = name;
this.price = price;
this.maxspeed = maxspeed;
}

对应的配置文件就可以更改为:

<object id="car1" type="Spring_constructor.Car, Spring_constructor"  >
<constructor-arg value="BMW" type="string" index="" />
<constructor-arg value="" type="int" index=""/>
<constructor-arg value="" type="int" index=""/>
</object>

通过type与index属性来确定我们要传入的参数具体是第几个参数,类型是什么,index初始值为0.

当我们配置的值有特殊字符时, 我们可以通过<![CDATA[]]> 来配置,如下代码:

 <constructor-arg>
<value><![CDATA["BMW"]]></value>
</constructor-arg>

代码下载