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

来源:互联网 发布:淘宝提升信誉的方法 编辑:程序博客网 时间:2024/05/22 06:22
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;  }}

    


0 0
原创粉丝点击