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

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>

代码下载

最新文章

  1. iOS 8 界面设计 PSD 模板(iPhone 6),免费下载
  2. Net预编译 真的好用与否
  3. Codeforces Round #198 (Div. 2) D. Bubble Sort Graph (转化为最长非降子序列)
  4. iOS-设计模式之代理反向传值
  5. 1711: [Usaco2007 Open]Dingin吃饭
  6. TwenLite源码阅读
  7. ASP.NET MVC AJAX的调用示例
  8. Python学习日记:day7-----集合
  9. (二叉树 递归 DFS) leetcode 100. Same Tree
  10. 记录一次mongodb因网络问题导致shard节点异常
  11. from __future__ import print_function的作用
  12. MRPT编译
  13. N的阶乘:高精度
  14. Android WebView 详解
  15. java 基本数据类型及自动类型提升
  16. java 读取execl文件
  17. canvas绘制文本
  18. SQL语句的执行顺序 1&gt;优先执行,然后依数字排序
  19. Eye Protection FAQ
  20. iOS7 自己定义动画跳转

热门文章

  1. [Go语言学习]之一:搭建单元测试环境
  2. java模式之装饰模式
  3. [置顶] ROS探索总结(十一)——机器视觉
  4. 64位linux报错Could not initialize class java.awt.image.BufferedImage
  5. Python高手之路【十二】面向对象设计模式
  6. 关于angularjs的$state.go()与ui-sref传参问题
  7. 【JS学习笔记】第一个JS效果——鼠标提示框
  8. Meterpreter
  9. [UWP小白日记-12]使用新的Composition API来实现控件的阴影
  10. JS 常用功能收集