依赖注入

依赖注入

以下示例使用基于 XML 的配置元数据进行基于 setter 的 DI。Spring XML 配置文件的一小部分如下指定了一些 bean 定义:

以下示例显示了相应的 ExampleBean 类:

Java

Kotlin

public class ExampleBean {

private AnotherBean beanOne;

private YetAnotherBean beanTwo;

private int i;

public void setBeanOne(AnotherBean beanOne) {

this.beanOne = beanOne;

}

public void setBeanTwo(YetAnotherBean beanTwo) {

this.beanTwo = beanTwo;

}

public void setIntegerProperty(int i) {

this.i = i;

}

}

class ExampleBean {

lateinit var beanOne: AnotherBean

lateinit var beanTwo: YetAnotherBean

var i: Int = 0

}

在前面的例子中,声明了 setter 来匹配 XML 文件中指定的属性。以下例子使用基于构造函数的 DI:

以下示例显示了相应的 ExampleBean 类:

Java

Kotlin

public class ExampleBean {

private AnotherBean beanOne;

private YetAnotherBean beanTwo;

private int i;

public ExampleBean(

AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {

this.beanOne = anotherBean;

this.beanTwo = yetAnotherBean;

this.i = i;

}

}

class ExampleBean(

private val beanOne: AnotherBean,

private val beanTwo: YetAnotherBean,

private val i: Int)

bean 定义中指定的构造函数参数用作 ExampleBean 构造函数的参数。

现在考虑此示例的一个变体,其中 Spring 被告知调用 static 工厂方法而不是使用构造函数来返回对象实例:

以下示例显示了相应的 ExampleBean 类:

Java

Kotlin

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;

}

}

class ExampleBean private constructor() {

companion object {

// 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.

@JvmStatic

fun createInstance(anotherBean: AnotherBean, yetAnotherBean: YetAnotherBean, i: Int): ExampleBean {

val eb = ExampleBean (...)

// some other operations...

return eb

}

}

}

static 工厂方法的参数由 元素提供,与实际使用构造函数的方式完全相同。工厂方法返回的类类型不必与包含 static 工厂方法的类类型相同(尽管在此示例中是相同的)。实例(非静态)工厂方法也可以以基本相同的方式使用(除了使用 factory-bean 属性而不是 class 属性),因此我们在此不讨论这些细节。

🎀 相关推荐

如何切换成手写输入法键盘
🎯 365bet亚洲

如何切换成手写输入法键盘

📅 07-31 👀 7443
【京东优评】热卖商品
🎯 bt365体育平台3

【京东优评】热卖商品

📅 07-11 👀 7315
集合理論符號表
🎯 bt365体育平台3

集合理論符號表

📅 10-26 👀 1328