第一個Spring.NET的程式
建立項目
項目名稱為:SpringSample,NameSpace為“OKEC.Sample.Spring”。
添加HelloTest類
HelloTest.cs
using System;
namespace OKEC.Sample.Spring
{
/// <summary>
/// HelloTest 的摘要說明。
/// </summary>
public class HelloTest
{
public HelloTest()
{
//
// TODO: 在此處添加建構函式邏輯
//
}
public void Test()
{
Console.WriteLine("This is Spring.NET Sample Test!");
Console.WriteLine("Please press Enter close the windows!");
Console.ReadLine();//讓程式停留,斷行符號關閉。
}
}
}
添加Spring.NET的設定檔
檔案名稱:Spring_bean.xml,屬性設定為:內嵌資源/ Embedded Resource<?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="Hello" type="OKEC.Sample.Spring.HelloTest,SpringSample" />
</objects>
建立Spring.NET的容器初始化對像
SpringContext.cs
using System;
using Spring.Core;
using Spring.Aop;
using System;
using Spring.Core;
using Spring.Aop;
using Spring.Context;
using Spring.Context.Support;
namespace OKEC.Sample.Spring
{
/// <summary>
/// SpringFactory 的摘要說明。
/// </summary>
public class SpringContext
{
public SpringContext()
{
//
// TODO: 在此處添加建構函式邏輯
//
}
private static bool isInit = false;
private static IApplicationContext context;
public static void init()
{
string[] xmlFiles = new string[1];
xmlFiles[0] = "assembly://SpringSample/OKEC.Sample.Spring/Spring_bean.xml";
context = new XmlApplicationContext(xmlFiles);
isInit = true;
}
public static IApplicationContext Context
{
get{
if(!isInit)
{
init();
}
return context;
}
}
}
}
添加啟動程式
StartMain.csusing System;
namespace OKEC.Sample.Spring
{
/// <summary>
/// StartMain 的摘要說明。
/// </summary>
public class StartMain
{
public StartMain()
{
//
// TODO: 在此處添加建構函式邏輯
//
}
[STAThread]
static void Main()
{
//Startup Spring Content
SpringContext.init();
//Test Spring IOC
HelloTest test = (HelloTest)SpringContext.Context.GetObject("Hello");
test.Test();
}
}
}
運行程式
結果為:
This is Spring.NET Sample Test!
Please press Enter close the windows!
你的第一個Spring.NET的程式成功了!
文檔中的項目原始碼請從以下地址下載:
http://www.springframework.cn/read.php?fid=8&tid=2&toread=1
完整的文檔請下載PDF文檔:
http://www.springframework.cn/read.php?fid=2&tid=1&toread=1