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>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpModules>
<!-- Spring 提供的 Module -->
<add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
</httpModules>
<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>
</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、效果图


浙公网安备 33010602011771号