Spring3.0学习笔记文档的官方网站(六)--3.4.1

时间:2022-07-26 08:20:08

3.4 依靠

3.4.1 依赖注入

    依赖注入两种方式:基于构造函数DI、基于setter方法DI。

3.4.1.1 基于构造函数DI

    参数是引进一个对象的。和缺乏父母之前-子类关系:

package x.y;

public class Foo {

  public Foo(Bar bar, Baz baz) {
// ...
}
}
<beans>
<bean id="foo" class="x.y.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
</bean> <bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/> </beans>

当使用简单类型时。spring不好确定value的类型。

package examples;

public class ExampleBean {

  // No. of years to the calculate the Ultimate Answer
private int years; // The Answer to Life, the Universe, and Everything
private String ultimateAnswer; public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>

或者能够使用index来指定參数要依照什么样的顺序设置。

<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" value="7500000"/>
<constructor-arg index="1" value="42"/>
</bean>

对spirng3.0来讲,还能够使用name来指定要设置的属性名。

<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg name="years" value="7500000"/>
<constructor-arg name="ultimateanswer" value="42"/>
</bean>

要让这种方法生效,要记得:your code must be compiled with the debug flag enabled(啥意思?)或者要使用@ConstructorProperties

package examples;

public class ExampleBean {

  // Fields omitted

  @ConstructorProperties({"years", "ultimateAnswer"})
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}

3.4.1.2 基于setter方法的DI

3.4.1.3 依赖解析过程

    容器在创建之后。会对每一个bean进行验证,包含验证bean引用的属性是否是有效的。可是bean引用的properties仅仅有在bean创建之后才会被创建。

单例bean在容器被创建的时候就被创建。其它的bean仅仅有在被请求才实用到。

    Spring设置properties或者解决依赖尽可能的晚。

A依赖于B,那么B会先被创建,然后才创建A。

3.4.1.4 DI样例

    使用静态工厂方法,传參数。

<bean id="exampleBean" class="examples.ExampleBean"
factory-method="createInstance">
<constructor-arg ref="anotherExampleBean"/>
<constructor-arg ref="yetAnotherBean"/>
<constructor-arg value="1"/>
</bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean {

  // a private constructor
private ExampleBean(...) {
...
} // a static factory method; the arguments to this method can be
// considered the dependencies of the bean that is returned,
// regardless of how those arguments are actually used.
public static ExampleBean createInstance (
AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) { ExampleBean eb = new ExampleBean (...);
// some other operations...
return eb;
}
}

版权声明:本文博客原创文章,博客,未经同意,不得转载。