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

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

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>

 

代码下载

 

转载于:https://www.cnblogs.com/JeremyLuBlog/p/6269466.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值