春天的订单依赖注入是什么? [英] Whats is the order dependency injection in spring?

查看:70
本文介绍了春天的订单依赖注入是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对弹簧依赖注入有疑问。
我需要知道依赖项是按照XML中声明的顺序注入的,还是
没有这样的顺序。

I have a question regarding spring dependency injection. I need to know whether dependency gets injected in the order in which it has been declared in the XML or there is no order as such.

示例:

<bean id="empBean" class="com.test.EmployeeBean">
      <property name="jdbcTemplate" ref="jdbcTemplate" />
       <property name="empAddress" ref="empAddress" />
    </bean>

我们可以保证总是 jdbcTemplate empName 之前初始化?请帮助

Can we guarantee that always jdbcTemplate will be initialized before empName? Please help

推荐答案

您不能保证将它们以任何特定顺序注入,因此您应该设计Bean,使其不会没关系-这很容易实现。

You cannot guarantee that these will be injected in any particular order, and you should design your beans such that it doesn't matter -- which is easy to achieve.

所以此类是不好的代码,因为在bean创建之后,其状态将根据Spring注入的顺序而有所不同。 :

So this class is bad code, because its state after bean-creation will differ depending on the order Spring happens to inject:

public class BadClass {
    private String foo = "";
    private String foobar = "";

    public void setFoo(String foo) {
        this.foo = foo;
    }

    public void setBar(String bar) {
        this.foobar = foo + bar;
    }

    public String toString() {
        return foobar;
    }
}

原因:

 BadClass c = new BadClass(); 
 c.setFoo("foo");
 c.setBar("bar"); 
 return c.toString()` 

... return $ foobar

... returns "foobar".

 BadClass c = new BadClass(); 
 c.setBar("bar"); 
 c.setFoo("foo");
 return c.toString()` 

... return bar

... returns "bar".

许多人认为使用构造函数注入是最佳实践,在这种情况下,所有注入都将在一次调用中

Many people think it's best practice to use constructor injection, in which case all the injections will occur in one invocation of the constructor.

public class BetterClass {
    private String foo = "";
    private String foobar = "";

    public BetterClass(String foo, String bar) {
        this.foo = foo;
        this.foobar = foo + bar;
    }

    public String toString() {
        return foobar;
    }
}

这篇关于春天的订单依赖注入是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆