Spring.NET学习实践(2) ---修改下我们的小例子

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 = "TestSpringNetTestHelloWorld.HelloWorld 指明实现服务的组件类
逗号后的SpringTest是组件所在的模块
 
代码中我们只需要修改注册方式即可。
 
IApplicationContext context = ContextRegistry.GetContext();

运行下,OK.  

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值