Spring.Net

http://blog.csdn.net/dyllove98/article/details/8604166

说明:在最开始推荐一下刘冬的博客,他的博客提供了一些很好的范例,可以用于快速入门!本文是针对刘冬博客前两章内容的整理笔记,当然有部分增加和省去的部分,方便日后查阅,所以建议先读刘冬的博客园!本文不再赘述XML、反射,设计模式、解耦相关理论、依赖注入概念!

博客地址:http://www.cnblogs.com/GoodHelper/archive/2009/11/20/SpringNet_Index.html

Spring.NET官网:http://www.springframework.net/

 

一、环境部署:

照着刘冬的博客和中文文档的配置方法,我都没法正常搭起Spring.NET的环境,现在给一个自己总结的靠谱的:

1.新建一个控制台应用程序,添加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="assembly://程序集名称/项目名称/Objects.xml"/>
    </context>
  </spring>
</configuration>
复制代码

其中resource的配置方式是使用的XML方式,毕竟我们不希望把对象写到App.config里。

2.添加Objects.xml文件,设置属性-生成操作为“嵌入的资源”:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
</objects>

我们的对象就写在这个配置文件里。

3.添加对Common.Logging.dll和Spring.Core.dll的引用,使用AOP请引用Spring.AOP.dll。

4.建立解决方案文件夹“Schema”,拷入"源码目录docschema”当中的xsd,用于智能提示。

至此基本环境搭建完毕。

 

二、获取对象所用的API

Spring.NET 的对象都是在XML里定义的,建议使用IApplicationContext,通过继承关系就能看出来它所包含的功能要比IObjectFactory 要多(刘冬博客用的就是IObjectFactory作为示例)。IoC容器的底层实际就是 Dictionary<string,object> 所以需要转换类型,这里也体现了Spring.NET的一个诟病——性能问题。

//获取上下文

IApplicationContext ctx = Spring.Context.Support.ContextRegistry.GetContext();

//创建对象

对象类型 obj = ctx.GetObject("对象名") as 对象类型;

 

 

三、object节的基本配置:

Spring.NET的对象需要配置在objects节下,object节的id是对象名,是上面API方法的参数,后面是完整类型名称。

1.如果类含有构造函数,通过构造函数创建对象

<object id="personDao" type="CreateObjects.PersonDao, CreateObjects" />

2.创建内部类的对象:

<object id="person" type="CreateObjects.PersonDao+Person, CreateObjects" />

3.静态工厂(将创建知识封装到一个静态方法当中)

<object id="staticObjectsFactory" type="CreateObjects.StaticObjectsFactory, CreateObjects" factory-method="CreateInstance"/>

4.把工厂对象IOC,然后调用工厂对象创建实例

<object id="instanceObjectsFactory" type="CreateObjects.InstanceObjectsFactory, CreateObjects" /><!--工厂-->

<object id="instancePersonDao" factory-method="CreateInstance" factory-object="instanceObjectsFactory" /> <!--创建的对象-->

5.泛型需要转译左尖括号

<object id="genericClass" type="CreateObjects.GenericClass&lt;int>, CreateObjects" />

 

四、object节的属性:

1.默认是单例对象,如果想让对象不单例,需要配置参数

<object id="person" type="SpringNetScop.Person, SpringNetScop" singleton="false" />

2.默认是在IOC容器初始化时创建好对象,可以配置参数让对象在第一次运行时创建

<object id="personServer" type="SpringNetScop.PersonServer, SpringNetScop" lazy-init="true" />

 

五、object的子节点配置:

1. property用于给属性赋值

<object id="modernPerson" type="SpringNetIoC.ModernPerson, SpringNetIoC">

         //设置字段属性

         <property name="Name" value="李刚 "/>

         //注入其他类型的对象作为自己的属性,需要配置computer对象

<property name="Tool" ref="computer"/>

</object>

2.设值注入

<object id="modernPerson" type="SpringNetIoC.ModernPerson, SpringNetIoC">

<property name="Friend">

  <object type="SpringNetDi.Person, SpringNetDi">

      <property name="Name" value="Beggar"/>

      <property name="Age" value="23"/>

      <property name="Friend" ref="person"/>

    </object>

</property>

</object>

3.设定构造函数的参数,构造注入:

<object id="personDao" type="SpringNetDi.PersonDao, SpringNetDi">

  <constructor-arg name="argPerson" ref="person"/>

  <constructor-arg name="intProp" value="1"/>

</object>

4.注入List

<property name="Years">

  <list element-type="int">

    <value>1992</value>

    <value>1998</value>

    <value>2000</value>

  </list>

</property>

5.注入Dictionary

<property name="HappyTimes">

  <dictionary key-type="string" value-type="object">

    <entry key="第一开心" value="每天都能睡一个好觉"/>

    <entry key="第二开心" value-ref="happy"/>

  </dictionary>

</property>

 

六、AOP的API

实质上就是在运行时根据类型信息反射创建一个类的代理类,并调用用户写的通知方法,从这个机制上就能看出性能不会太高,个人建议对服务层之类的接口进行AOP,没必要的话不要轻易AOP。另外AOP也可以通过XML来配(见刘冬的博客)。

//1.创建目标类的对象(要拦截的对象)

IXXX target = new XXX();

//2.创建代理工厂

ProxyFactory factory = new ProxyFactory(target);

//3.定义通知

factory.AddAdvice(new AroundAdvise());

factory.AddAdvice(new BeforeAdvise());

factory.AddAdvice(new AfterReturningAdvise());

factory.AddAdvice(new ThrowsAdvise());

//4.通过代理工厂得到目标对象的代理对象

IXXX proxy = (IXXX)factory.GetProxy();

//5.通过代理调用方法

Proxy.Method();

1、配置List:

1)值类型或string的List

public IList<string> BanedChangeShippingSkuList{set;get;}

<object name="IOrderService" type="XX.XXX.XXX.BLL.Orders.OrderService, XX.XXX.XXX.BLL">
    <property name="ProductService" ref="IProductService" />
    <property name="CancelOrderStayDao" ref="CancelOrderStayDao" />
    <property name="CacheService" ref="MemcachedService" />
    <property name="BanedChangeShippingSkuList">
      <list>
        <value>331</value>
        <value>334</value>
        <value>972</value>
        <value>0</value>
      </list>
    </property>
  </object>


    2)引用类型的IList    public IList<IShippingDecorator> ShippingDecoratorList { private get; set; }

<object name="IShippingService" type="XX.XXX.XXX.BLL.Orders.ShippingService, XX.XXX.XXX.BLL">
    <property name="ShippingDecoratorList">
      <list element-type="XXX.XXX.XXX.BLL.Orders.Rules.IShippingDecorator, XXX.XXX.XXX.BLL">
        <object type="XXX.XXX.XXX.BLL.Orders.Rules.RussiaShippingDecorator, XXX.XXX.XXX.BLL">
        </object>

        <object type="XXX.XXX.XXX.BLL.Orders.Rules.OnlyStandardShippingDecorator, XXX.XXX.XXX.BLL">
          <property name="OnlyStandardShippingSKUList">
            <list>
              <value>331</value>
              <value>334</value>
              <value>972</value>
            </list>
          </property>
        </object>
      </list>
    </property>
  </object>

2、Dictionary:

        public IDictionary<string, string> EmailServerList { get; set; }

  <!-- AppSettings设置信息 -->
  <object id="AppSettings" type="XXXX.Passport.Common.Settings.AppSettings, XXXX.Passport.Common">
    <property name="EmailFrom" value="${EmailFrom}"/>
    <property name="MssUserName" value="${MSS_Clinet}"/>
    <property name="LoginHelpUrl" value="${LoginHelpUrl}"/>
    <property name="UserName" value="${UserName}"/>
    <property name="Password" value="${Password}"/>
    <property name="Host" value="${Host}"/>
    <property name="GlobalResourcesAddress" value="${GlobalResourcesAddress}"/>
    <property name="PassportDomain" value="${PassportDomain}"/>
    <property name="CookieDomain" value="${CookieDomain}"/>
    <property name="TimeZoneShift" value="${TimeZoneShift}"/>
    <property name="RegisterViewDetailUrl" value="${RegisterViewDetailUrl}"/>
    <property name="CMSBannerKey" value="${CMSBannerKey}"/>
    <property name="ShowOldPassportLink" value="${ShowOldPassportLink}"/>
    <property name="EmailServerList">
      <dictionary key-type="string" value-type="string">
        <entry key="qq.com" value="http://mail.qq.com" />
        <entry key="163.com" value="http://mail.163.com" />
        <entry key="126.com" value="http://mail.126.com" />
        <entry key="gmail.com" value="http://mail.google.com" />
        <entry key="hotmail.com" value="http://mail.hotmail.com" />
        <entry key="live.com" value="http://mail.live.com" />
        <entry key="yahoo.com" value="http://mail.yahoo.com" />
        <entry key="aol.com" value="http://mail.aol.com" />
        <entry key="mail.ru" value="http://mail.mail.ru" />
        <entry key="yandex.ru" value="http://mail.yandex.ru" />
        <entry key="foxmail.com" value="http://mail.foxmail.com" />
        <entry key="yeah.net" value="http://mail.yeah.net" />
        <entry key="sina.com" value="http://mail.sina.com" />
        <entry key="sina.cn" value="http://mail.sina.cn" />
        <entry key="sohu.com" value="http://mail.sohu.com" />
        <entry key="hongkong.com" value="http://mail.hongkong.com" />
        <entry key="mail.com" value="http://mail.com" />
        <entry key="lycos.com" value="http://mail.lycos.com" />
        <entry key="icqmail.com" value="http://www.icqmail.com" />
        <entry key="e-mail.ru" value="http://e-mail.ru/" />
        <entry key="firstname.com" value="http://www.firstname.com" />
        <entry key="onebox.com" value="http://www.onebox.com/" />
        <entry key="germanmail.com" value="http://www.germanmail.com/" />
        <entry key="vsnl.com" value="http://login.vsnl.com/" />
      </dictionary>
    </property>
  </object>

AOP配置发送邮件功能:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
         xmlns:aop="http://www.springframework.net/aop">

  <!-- 发送邮件的切面功能点 -->
  <object id="emailAdvisor" type="Spring.Aop.Support.SdkRegularExpressionMethodPointcut, Spring.Aop">
    <property name="Patterns">
      <list>
        <value>TTTT.Passport.Service.AccountService.RegisterAccount</value>
        <value>TTTT.Passport.Service.AccountService.ActiveAccount</value>
        <value>TTTT.Passport.Service.AccountService.SendActivateEmail</value>
        <value>TTTT.Passport.Service.AccountService.SendResetPasswordEmail</value>
        <value>TTTT.Passport.Service.AccountService.ManualRegisterAndBind</value>
      </list>
    </property>
  </object>

  <aop:config>
    <aop:advisor pointcut-ref="emailAdvisor" advice-ref="SendEmailAdvice"/>
  </aop:config>
 
  <object id="SendEmailAdvice" type="TTTT.Passport.Common.Advice.SendEmailAdvice, TTTT.Passport.Common"/>

</objects>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Aop;
using TTTT.Passport.Common.Email;

namespace TTTT.Passport.Common.Advice
{
    /// <summary>
    /// 发邮件的AOP切面功能
    /// 此切面为方法正常运行完成后触发
    /// </summary>
    public class SendEmailAdvice : IAfterReturningAdvice
    {
        /// <summary>
        /// 在方法操作完成后运行
        /// </summary>
        /// <param name="returnValue"></param>
        /// <param name="method"></param>
        /// <param name="args"></param>
        /// <param name="target"></param>
        public void AfterReturning(object returnValue, System.Reflection.MethodInfo method, object[] args, object target)
        {
            //-----------------------------------------------
            // 循环查找方法参数
            //-----------------------------------------------
            for (int i = 0; i < args.Length; i++)
            {
                // 如果参数是EmailFactroy则执行发邮件操作
                if (args[i] is EmailFactroy)
                {
                    EmailFactroy email = args[i] as EmailFactroy;
                    try
                    {
                        // 发送邮件
                        email.Send();
                    }
                    catch (Exception ex)
                    {
                        Util.Log.Error(ex);
                        throw new EmailException(ex.Message, ex);
                    }
                    break;
                }
            }
            return;
        }
    }
}

原文地址:https://www.cnblogs.com/cxzdy/p/3964195.html