网上有很多Spring.Net的入门教程,并提供了详细的Demo,但是照着一步步做下来,却会出现各种错误。
经研究,攻克了这些问题,将Demo成功运行起来了。
现将极度简化的Demo总结如下:
1. 创建一个控制台程序,项目名称为ConsoleApplication1
2. 添加一个类A
namespace namespaceA
{
public class A
{
public A()
{
Console.WriteLine("创建了A的实例");
}
}
}
3. 引用Spring.net需要的dll,Spring.Core.dll和Common.Logging.dll,很多教程中漏掉了后者,导致运行报错
4. 添加App.config
<?xml version="1.0"?>
<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>
<object name="a" type="namespaceA.A, ConsoleApplication1" />
</objects>
</spring>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
这里也是个容易报错的地方,原因是<startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup>影响到了Spring对.net和运行时版本的指定,解决方法是把<startup>...</startup>写在Spring节点的后面,或者直接删除<startup>...</startup>
5. 创建对象
class Program
{
static void Main(string[] args)
{
IApplicationContext context = ContextRegistry.GetContext();
A a = (A)context.GetObject("a");
}
}
上面1-4都就绪之后,第5部调用创建对象的时候也容易出错:Error creating context 'spring.root': Could not load type from string value'...'
原因是配置文件中的object的type没写对,type的格式为命名空间.类名,程序集名
比如本例中,<object name="a" type="namespaceA.A, ConsoleApplication1" />
命名空间是namespaceA, 类名是A,程序集名是ConsoleApplication1
1194

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



