Spring.NET学習ノート(1)-基本依存注入
Springを勉強しないで、システムはそのまま走れます.Springを覚えたら、覚えていない前とどれぐらいの差があるかが分かります.ずっとSpringを使っていると、Springを使わないでプログラムを書くと手がつけられないような気がします.Springは容器です.プログラムを組み立てるために使います.
一.依存注入
三つの方式に分ける
(1)構造注入
3.1
一.依存注入
三つの方式に分ける
(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">
<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;
}
}
MyValue CalculatorのComputteValue方法を置き換えると、IMethodReplacerインターフェースのImplement方法が実現されます.<object id="myValueCalculator" type="Examples.MyValueCalculator, ExampleAssembly">
<replaced-method name="ComputeValue" replacer="replacementComputeValue">
<arg-type match="String"/>
replaced-method>
object>
<object id="replacementComputeValue" type="Examples.ReplacementComputeValue, ExampleAssembly"/>
この方法は明らかに変態で、パッケージを完全に破壊しました.