Spring.net 学习IOC------通过构造器注入
2024-10-18 23:23:28
别的不多说,咱们先上代码
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>
最新文章
- iOS 8 界面设计 PSD 模板(iPhone 6),免费下载
- Net预编译 真的好用与否
- Codeforces Round #198 (Div. 2) D. Bubble Sort Graph (转化为最长非降子序列)
- iOS-设计模式之代理反向传值
- 1711: [Usaco2007 Open]Dingin吃饭
- TwenLite源码阅读
- ASP.NET MVC AJAX的调用示例
- Python学习日记:day7-----集合
- (二叉树 递归 DFS) leetcode 100. Same Tree
- 记录一次mongodb因网络问题导致shard节点异常
- from __future__ import print_function的作用
- MRPT编译
- N的阶乘:高精度
- Android WebView 详解
- java 基本数据类型及自动类型提升
- java 读取execl文件
- canvas绘制文本
- SQL语句的执行顺序 1>;优先执行,然后依数字排序
- Eye Protection FAQ
- iOS7 自己定义动画跳转
热门文章
- [Go语言学习]之一:搭建单元测试环境
- java模式之装饰模式
- [置顶] ROS探索总结(十一)——机器视觉
- 64位linux报错Could not initialize class java.awt.image.BufferedImage
- Python高手之路【十二】面向对象设计模式
- 关于angularjs的$state.go()与ui-sref传参问题
- 【JS学习笔记】第一个JS效果——鼠标提示框
- Meterpreter
- [UWP小白日记-12]使用新的Composition API来实现控件的阴影
- JS 常用功能收集