Spring.NET学习笔记(1)-基本依赖注入
2009-08-25 11:12 Clingingboy 阅读(1245) 评论(0) 编辑 收藏 举报不学Spring,系统照样能跑,学会了Spring会发现跟没学会之前也多大差别,一直在用Spring以后就会感觉不用Spring写程序就好像无从下手,Spring就是一容器,用以组装程序而用。
一.依赖注入
分三种方式
(1)构造注入
<object id="foo" type="X.Y.Foo, Example"> <constructor-arg ref="bar"/> <constructor-arg ref="baz"/> </object> <object id="bar" type="X.Y.Bar, Example"/> <object id="baz" type="X.Y.Baz, Example"/>
(2)Setter属性注入
<object id="exampleObject" type="Examples.ExampleObject, ExamplesLibrary"> <!-- setter injection using the ref attribute --> <property name="objectOne" ref="anotherExampleObject"/> <property name="objectTwo" ref="yetAnotherObject"/> <property name="IntegerProperty" value="1"/> </object> <object id="anotherExampleObject" type="Examples.AnotherObject, ExamplesLibrary"/> <object id="yetAnotherObject" type="Examples.YetAnotherObject, ExamplesLibrary"/>
(3)方法注入
3.1
public class TestObjectFactory { public const string TheName = "Old Goriot"; public const int TheAge = 78; public virtual object GetObject() { return new TestObject(TheName, TheAge); } }
<object id='factory' type='Spring.Objects.Factory.Support.TestObjectFactory, Spring.Core.Tests'> <lookup-method name='GetObject' object='target'/> </object> <object id='target' type='Spring.Objects.TestObject, Spring.Core.Tests' singleton='false'> <property name='name' value='Fiona Apple'/> <property name='age' value='47'/> </object>
3.2方法替换
public class MyValueCalculator { public virtual string ComputeValue(string input) { // ... some real code } // ... some other methods } public class ReplacementComputeValue : Spring.Objects.Factory.Support.IMethodReplacer { public object Implement(object target, MethodInfo method, object[] arguments) { // get the input value, work with it, and return a computed result... string value = (string)arguments[0]; // compute... return result; } }
将MyValueCalculator 的ComputeValue方法替换成,实现IMethodReplacer 接口的Implement方法
<object id="myValueCalculator" type="Examples.MyValueCalculator, ExampleAssembly"> <!-- arbitrary method replacement --> <replaced-method name="ComputeValue" replacer="replacementComputeValue"> <arg-type match="String"/> </replaced-method> </object> <object id="replacementComputeValue" type="Examples.ReplacementComputeValue, ExampleAssembly"/>
这个方法明显很变态,完全破坏了封装,一般很少用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现