上一篇是通过代码来实现,这次准备通过配置XML文件来实现相同的功能。
一 新建工程
新建一个控制台程序,添加应用程序配置文件app.config
内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects" />
</context>
<objects xmlns="http://www.springframework.net">
<object id="HelloWorld" type="ConsoleApplication1.HelloWorld,ConsoleApplication1"></object>
</objects>
</spring>
</configuration> 代码:
using System;
using System.Collections.Generic;
using System.Text;
using Spring.Core;
using Spring.Context;
using Spring.Context.Support;
namespace ConsoleApplication1
...{
public interface SayHi
...{
string SayHello();
}
public class HelloWorld : SayHi
...{
public string SayHello()
...{
return "Hello, World!";
}
}
class Program
...{
static void Main(string[] args)
...{
try
...{
// Force Spring to load configuration
IApplicationContext ctx = ContextRegistry.GetContext();
SayHi o = ctx.GetObject("HelloWorld") as SayHi;
Console.Out.WriteLine(o.SayHello());
}
catch (Exception e)
...{
Console.Out.WriteLine(e);
}
finally
...{
Console.Out.WriteLine("--- Press <return> to quit ---");
Console.ReadLine();
}
}
}
}
添加引用:
Spring.Core.dll
Common.Logging.dll关联的dll,必须添加。刚开始的时候,因为没添加这个DLL,程序会报错
二 测试
跟代码实现的效果相同
三 备注
在写这个例子的时候,碰到了以下的错误,写一下,以备后查
"The context name passed to the GetContext method cannot be null or empty"
app.config的格式不正确
"Error instantiating context 'spring.root'."
app.config的格式不正确
"Spring.Context.Support.ContextRegistry”的类型初始值设定项引发异常"
没有引用Common.Logging.dll
本文介绍了一个使用XML配置文件实现依赖注入的例子。通过配置app.config文件并利用Spring框架,实现了对象的创建与方法调用。
266

被折叠的 条评论
为什么被折叠?



