反射 + 配置文件 实现IOC容器

IOC实现:

IOC容器我们仅仅停留在知道上是不行的,我们要动手做印象对更深刻,那么我给大家看一个代码,看看代码中IOC容器的实现。

代码实现:

创建一个类库:

解决方案的类库建立:

创建一个实体类:User:

<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Text;

namespace Spring.Demo.Model
{
    /// <summary>
    /// 用户类
    /// </summary>
    public class Users
    {
        /// <summary>
        /// 编号
        /// </summary>
        private int _oid;
        public int Oid
        {
            get { return _oid; }
            set { _oid = value; }
        }

        /// <summary>
        /// 姓名
        /// </summary>
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        /// <summary>
        /// 性别
        /// </summary>
        private string _sex;
        public string Sex
        {
            get { return _sex; }
            set { _sex = value; }
        }

        /// <summary>
        /// 年龄
        /// </summary>
        private int _age;
        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
    }
}</span>

创建IUsers的接口:

<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Text;
namespace Spring.Demo.Service
{
    public interface IUsers
    {
        /// <summary>
        /// 返回用户的详细信息的方法
        /// </summary>
        /// <returns></returns>
        string GetUserInfo();
    }
}
</span>

创建一个实现IUsers接口的实现类:

<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Text;
using Spring.Demo.Service;
using Spring.Demo.Model;

namespace Spring.Demo.Compontext
{
    public class UsersCompontents : IUsers
    {
        public UsersCompontents()
        { }

        #region 获取用户信息
        public string GetUserInfo()
        {
            Users user = new Users();
            user.Oid = 1;
            user.Name = "Beniao";
            user.Sex = "Boy";
            user.Age = 25;

            return string.Format("编号:{0}--->姓名:{1}--->性别:{2}--->年龄:{3}",
                user.Oid,
                user.Name,
                user.Sex,
                user.Age);
        }
        #endregion
    }
}</span>

创建测试类:

<span style="font-size:18px;">using ITOO.Library.Core.AOP;
using Spring.Context;
using Spring.Demo.Service;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace Sping.Demo.SimpleTest
{
    class Program
    {
        static void Main(string[] args)
        {

            IUsers studentChangeBll = SpringHelper.GetObject<IUsers>("Users");

            Console.WriteLine(studentChangeBll.GetUserInfo());
            Console.Read();
        }
    }
}</span>

在控制台程序中创建一个配置文件:

<span style="font-size:18px;"><?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">
      <!--这的配置根据实际的程序来的,UsersCompontents是程序集Spring.Demo.Compontext下的一个类-->
      <object name="Users"
              type="Spring.Demo.Compontext.UsersCompontents,Spring.Demo.Compontext"  singleton="false" >
      </object>
    </objects>
  </spring>
</configuration></span>

运行后,发现SpringHelper却小引用。我们一般写代码中我们是这样写的:

<span style="font-size:18px;">//从config文件中取得程序集信息
IApplicationContext context = ConfigurationManager.GetSection("spring/context")
                               as IApplicationContext;
//调用方法
//Users为config文件里的配置节
//<object name="Users"
//        type="Spring.Demo.Compontext.UsersCompontents,Spring.Demo.Compontent">
//</object>
IUsers user = context.GetObject("Users") as IUsers;</span>

这样我们就可以从配置文件中将对象取出来,但是我们都不想在代码中有多余的代码,不能每一次new对象的时候,我们都要写一遍这句话:IApplicationContext context = ConfigurationManager.GetSection("spring/context") as IApplicationContext;这样就增加了我们维护代码的成本,因此,我们将这句话封装起来,封装的代码是这样的:

创建一个类:SpringHelper:

<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context;
using Spring.Context.Support;

namespace ITOO.Library.Core.AOP
{
    public class SpringHelper
    {
        /// <summary>
        /// Spring容器上下文
        /// </summary>
        private static IApplicationContext SpringContext
        {
            get
            {
                return ContextRegistry.GetContext();
            }
        }

        /// <summary>
        /// 获取配置文件 配置的 对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objName"></param>
        /// <returns></returns>
        public static T GetObject<T>(string objName) where T : class
        {
            return (T)SpringContext.GetObject(objName);
        }
    }
}

</span>

以上的代码我们就可以将每次读取配置文件中的那句话去掉了,我们直接就可以写这样一句话就可以了:IUsers studentChangeBll = SpringHelper.GetObject<IUsers>("Users");

这里体现了封装的重要性,先前我在做AOP的时候,我的师傅看到了类似这样的代码的时候,他就跟我讨论过这个问题,我当时懵懵懂懂,没有进行下一步的行动,现在想想,问题出现在我根本没有动手去做,或者知识没有深入到那个层次,认识这个知识的方面没有那么深。所有问题,都要动手去做才行。

总结:

我们从上面的实践到分析之后,我们发现其实我们看似是新的东西,其实我们已经学习过了,就像IOC容器一样,我们学习过了反射和配置文件,我们发现其实IOC容器不就是反射和配置文件来实现的吗,反射和配置文件是我们在大话设计模式中就已经学习到了的东西,这都不是新的东西。一个看似复杂的东西,都是有简单的东西来组装成的,我们知道这个,就不会对新的东西有畏惧感了。

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-07-29 11:47:18

反射 + 配置文件 实现IOC容器的相关文章

深入理解Spring的IOC容器

IOC概述 IOC是Spring容器的内核,AOP.声明式事务等功能都依赖于此功能,它涉及代码解耦.设计模式.代码优化等问题的考量,我们将通过以下三个方面来深入理解IOC: IoC的初步理解 IoC的注入类型 构造器注入:通过调用类的构造函数,将接口实现的类通过构造函数变量传入. 属性注入:通过setter方法完成调用类所需依赖的注入,更加灵活方便. 接口注入:将调用类所有依赖注入的方法抽取到一个接口中,调用类通过实现该接口提供相应的注入方法. IoC的注入方式 Spring最为一个容器,通过配

【SSH进阶之路】一步步重构容器实现Spring框架——配置文件+反射实现IoC容器(十)

目录 [SSH进阶之路]一步步重构容器实现Spring框架--从一个简单的容器开始(八) [SSH进阶之路]一步步重构容器实现Spring框架--解决容器对组件的"侵入式"管理的两种方案--主动查找和控制反转(九) [SSH进阶之路]一步步重构容器实现Spring框架--配置文件+反射实现IoC容器(十) [SSH进阶之路]一步步重构容器实现Spring框架--彻底封装,实现简单灵活的Spring框架(十一)(未更新) 上上篇博文[SSH进阶之路]一步步重构容器实现Spring框架--

IOC容器

IOC概念 控制反转(Inversion of Control ),是一个重要的面向对象编程法则来削减计算机程序的耦合问题,也是轻量级的Spring框架的核心. 反射: 依赖注入(Dependency Injection): ICoreDbSession dbSession=CallContext.GetData("Dbsession") as ICoreDbsession; if (dbSession==null){ dbSession=SpringHelper.GetObject&

IoC容器实现原理

实例化 在实例化一个类时,它通过反射调用类中set方法将事先保存在HashMap中的类属性注入到类中. 依赖注入的另一种说法是“控制反转”,通俗的理解是:平常我们new一个实例,这个实例的控制权是我们程序员,而控制反转是指new实例工作不由我们程序员来做而是交给spring容器来做. IoC容器工作原理 大致分为BeanDefinition的定位.IoC容器初始化.依赖注入三个过程,具体说明如下: BeanDefinition的定位.对IoC容器来说,它为管理POJO之间的依赖关系提供了帮助,但

《Spring揭秘》(八)---- IoC容器及Bean的生命周期

Spring的IoC容器会以某种方式加载配置信息,然后根据这些信息绑定整个系统的对象,最终组装成一个可用的基于轻量级容器的应用系统.实现以上功能,分为两个阶段:容器启动阶段和Bean实例化阶段.而且Spring的IoC容器在每个阶段都加入了相应的扩展点,以便根据具体场景的需要加入自定义的扩展逻辑. 1 容器启动阶段 首先会通过某种途径加载配置信息,大部分情况下,容器需要依赖某些工具类(BeanDefinitionReader)对加载的配置信息进行解析和分析,并将分析后的信息编组为相应的BeanD

Spring框架学习[IoC容器高级特性]

1.通过前面4篇文章对Spring IoC容器的源码分析,我们已经基本上了解了Spring IoC容器对Bean定义资源的定位.读入和解析过程,同时也清楚了当用户通过getBean方法向IoC容器获取被管理的Bean时,IoC容器对Bean进行的初始化和依赖注入过程,这些是Spring IoC容器的基本功能特性.Spring IoC容器还有一些高级特性,如使用lazy-init属性对Bean预初始化.FactoryBean产生或者修饰Bean对象的生成.IoC容器初始化Bean过程中使用Bean

Spring—IOC容器如何实例话Bean

前言  传统应用程序可以通过new和反射的方式来实例化Bean.而Spring Ioc容器则需要根据配置元数据使用反射机制来创建Bean.在Spring Ioc容器中根据Bean创建Bean实例有以下几种方式. (1).使用构造器实例化Bean (2).使用静态工厂实例化Bean (3).使用实例工厂实例化Bean 一.使用构造器实例化Bean:Spring IoC容器能使用默认空构造器也能使用有参数构造器两种方式创建Bean. (a).使用空构造器进行定义,使用此种方式,class属性指定的类

使用Spring.NET的IoC容器

使用Spring.NET的IoC容器 0. 辅助类库 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SpringDemo.Pub { public static class Pub { public static string ServiceNameA = "SpringDemo.Lib.Oracle.OracleDatabase"; pub

JAVAWEB开发之Spring详解之——Spring的入门以及IOC容器装配Bean(xml和注解的方式)、Spring整合web开发、整合Junit4测试

Spring框架学习路线 Spring的IOC Spring的AOP,AspectJ Spring的事务管理,三大框架的整合 Spring框架概述 什么是Spring? Spring是分层的JavaSE/EE full-stack(一站式)轻量级开源框架. 所谓分层: SUN提供的EE的三层结构:web层.业务层.数据访问层(也称持久层,集成层). Struts2是web层基于MVC设计模式框架. Hibernate是持久的一个ORM的框架. 所谓一站式:Spring框架有对三层的每层解决方案.