spring 属性注入

Spring的核心技术室依赖注入,下面是依赖注入之属性注入的实现过程,牛刀小试,请看效果。

1、首先添加Spring.Web引用。本例中是使用分层思想来演示的,下面是项目的结构和UserModel类的内容,为了简单操作,只有一个Name属性

2、修改Web.Config文件,配置注入环境

复制代码
    <configSections>
        <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/>
      <!-- 支持在 web.config 中定义对象 -->
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
        </sectionGroup>
    </configSections>
添加Spring的SectionGroup
复制代码
复制代码
 <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <httpModules>
      <!-- Spring 提供的 Module  -->
      <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
    </httpModules>
添加HttpModule配置
复制代码
复制代码
 <httpHandlers>
      <add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
      <!-- 取消 Spring.NET 对于 Web 服务的处理 -->
      <!--<add verb="*" path="*.asmx" type="Spring.Web.Services.WebServiceHandlerFactory, Spring.Web"/>-->
      <add verb="*" path="ContextMonitor.ashx" type="Spring.Web.Support.ContextMonitor, Spring.Web"/>
      <add verb="*" path="*.ashx" type="Spring.Web.Support.DefaultHandlerFactory, Spring.Web"/>
    </httpHandlers>
添加HttpHandler配置
复制代码
复制代码
    </configSections>
    <spring>
        <context>
      <!---外部文件注入-->
      <!--<resource uri="Configration.xml"/>-->
      <!--<resource uri="config://spring/objects"/>-->
    </context>

    <objects>
      <!--id为自定义的id和下面要注入的页面property节点下的framework要保持一致,type为要注入的属性的所在类 -->
      <object id="framework" type="Spring.Model.UserModel,Spring.Model">
        <!--name为注入的属性,value为属性的值-->
        <property name="Name" value="Spring.NET"/>
      </object>
      
      <!--页面注入-->
      <object type="~/Default.aspx">
        <property name="UserModel" ref="framework"></property>
      </object>
    </objects>
    </spring>
依赖注入配置
复制代码

3、实现注入

复制代码
    /// <summary>
        /// 定义注入点
        /// </summary>
        public UserModel UserModel { set; get; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.UserModel != null)
            {
                Label1.Text = this.UserModel.Name;
            }
        }
实现注入
复制代码

4、效果图

posted @   竹林溪风  阅读(416)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示