代码改变世界

【原】[Spring.Net In Action 教程] 二、Spring.Net简单示例

2010-09-12 17:37  bugfly  阅读(678)  评论(1编辑  收藏  举报

这个是<<Spring In Action>>开篇示例。

 

1.项目总体部署结构

 

 

2.GreetingService接口。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    public interface GreetingService
    {
        void sayGreeting();
    }
}

 

3.GreetingService实现类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    class GreetingServiceImpl:GreetingService
    {
        protected string greeting;

        GreetingServiceImpl() { }

        GreetingServiceImpl(string greeting){
            this.greeting=greeting;
        }

        public void sayGreeting()
        {
            Console.WriteLine(greeting);
        }

        public void setGreeting(string greeting)
        {
            this.greeting = greeting;
        }
    }
}

 

4.SpringConfiguration.xml配置文件

配置文件
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation
="http://www.springframework.net
http://www.springframework.net/xsd/spring-objects.xsd"
>

<object id="xGreetingService" type="Model.GreetingServiceImpl, Model">
<property name="greeting" >
<value>Hello!Spring.NET</value>
</property>
</object>
</objects>

 

5.单元测试类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Model;
using Spring.Core;
using Spring.Context;
using Spring.Context.Support;
using Spring.Objects.Factory;

namespace NunitTest
{
    [TestFixture]
    class GreetingServiceTest
    {
        private GreetingService m_service;

        [TestFixtureSetUp]
        public void init()
        {
            string[] xmlPath = { "file://Spring/SpringConfiguration.xml"};
            IApplicationContext n_context = new XmlApplicationContext(xmlPath);
            IObjectFactory n_factory = (IObjectFactory)n_context;

            this.m_service = (GreetingService)n_factory.GetObject("xGreetingService");
        }

        [TestFixtureTearDown]
        public void release()
        {
            this.m_service = null;
        }

        [Test]
        public void test_sayGreeting()
        {
            this.m_service.sayGreeting();
        }
    }
}

 

6.运行结果

 

 

7.本示例代码

Demo