Spring.NET
学习实践(2
)
修改下我们的小例子:
在上一篇文章的最后,我们作了一个简单的例子,来使用Spring.NET,虽然这个例子真的是很简陋.
static
void Main(string[] args)
{
StaticApplicationContext context = new StaticApplicationContext();
context.RegisterPrototype("HelloWorld", typeof(HelloWorld), null);
SayHi o = context.GetObject("HelloWorld") as SayHi;
System.Windows.Forms.MessageBox.Show(o.SayHello());
}
现在我们来看看这个例子的流程。
1.申请容器
StaticApplicationContext
context = new StaticApplicationContext();
2
.注册服务
context.RegisterPrototype("HelloWorld", typeof(HelloWorld), null);
3
.获得服务
组件
SayHi
o = context.GetObject("HelloWorld") as SayHi;
4
.使用组件
System.Windows.Forms.MessageBox.Show(o.SayHello());
麻雀虽小五脏俱全,或许我们以后要面对要复杂的多Spring.NET代码,但是基本上会和
上面这个例子走类似的流程。
但是这个例子也不是很完美。因为我们在第二步注册服务时,使用的是代码配置的方式,如果我们象更换服务组件时,我们不得不来修改代码,是我们无法忍受的,简直回到原始时代了(关于代码配置还是配置文件配置的问题,Spring社区和其他构架社区一样配置文件配置的声音占了绝大多数,但是平心而论代码配置还是尤其擅长的地方的,至少不想一些人说的那么让人忍受不了,甚至是一无是处)。
现在我们换个方式,使用常见的XML配置方式来修改下我们的小例子。
首先修改我们的配置文件(web.config或是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="TestSpringNetTestHelloWorld.HelloWorld, SpringTest" >
</
object
>
</
objects
>
</
spring
>
</
configuration
>
很简单把,
<
object
id
=
"HelloWorld"type="TestSpringNetTestHelloWorld.HelloWorld, SpringTest" >
声明了一个
HelloWorld
的服务的组件配置
其中type是实现服务的组件
其中type是实现服务的组件
type
=
"TestSpringNetTestHelloWorld.HelloWorld
指明实现服务的组件类,
逗号后的SpringTest是组件所在的模块
代码中我们只需要修改注册方式即可。
IApplicationContext
context = ContextRegistry.GetContext();
运行下,OK.