之所以寫這篇文章是因為網上很多例子都是不可以用的,大多純粹是誤人子弟。
這篇文章純粹是一個HelloWorld,希望能幫到大家。至於配置里需要注意的地方可參考其他文章,這里僅列出可用的項目代碼及下載。
開發環境:VS2005(打了SP1的補丁)
步驟一:新建一個控制台項目
步驟二:引用Spring.Core.dll
步驟三:新建App.config代碼如下:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/> </sectionGroup> </configSections> <spring> <context> <resource uri="file://spring.xml.config"/> </context> </spring> </configuration>
步驟四:新建spring.xml.config(這個名字可自定,如需改名,則在App.config的rescource里也需一並修改),代碼如下:
<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net"> <object id="hello" type="SpringNetDemo.Hello"> <property name="HelloWord" value="Hello!你能看到這個證明你成功了!"/> </object> </objects>
步驟五:修改項目原來的Program.cs文件:
using System; using System.Collections.Generic; using System.Text; using Spring.Context; using Spring.Context.Support; namespace SpringNetDemo { public class Hello { private string helloword; public string HelloWord { get { return this.helloword; } set { this.helloword = value; } } } public class Program { static void Main(string[] args) { IApplicationContext context = ContextRegistry.GetContext(); Hello hello = (Hello)context.GetObject("hello"); Console.Write(hello.HelloWord); Console.Read(); } } }
說明:這里的hello.HelloWord就是Spring.Net通過xml的配置實現注入的。有問題的可以留言。
