Calling a static factory method with specific arguments to construct the bean is nearly equivalent, and this discussion treats arguments to a constructor and to a static factory method similarly.
与携带确定的参数调用一个静态工厂方法去构造一个bean是几乎相同,本次探讨以类似的方式处理构造函数和静态工厂方法的参数。【有点拗口】
The following example shows a class that can only be dependency-injected with constructor injection:
接下来的例子展示了一个只有依赖注入的注入构造器的类。
Java
public class SimpleMovieLister {
// the SimpleMovieLister has a dependency on a MovieFinder
private MovieFinder movieFinder;
// a constructor so that the Spring container can inject a MovieFinder
public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// business logic that actually uses the injected MovieFinder is omitted...
}
Kotlin
// a constructor so that the Spring container can inject a MovieFinder
class SimpleMovieLister(private val movieFinder: MovieFinder) {
// business logic that actually uses the injected MovieFinder is omitted...
}
Notice that there is nothing special about this class.
注意在这个类里并没有什么特别的。
It is a POJO that has no dependencies on container specific interfaces, base classes or annotations.
这是一个POJO类,不依赖容器中特定的接口,父类,或注解。
Constructor Argument Resolution
构造参数解析
Constructor argument resolution matching occurs by using the argument’s type.
构造参数解析匹配通过使用参数的类型而发生。
If no potential ambiguity exists in the constructor arguments of a bean definition, the order in which the constructor arguments are defined in a bean definition is the order in which those arguments are supplied to the appropriate constructor when the bean is being instantiated.
如果bean定义的构造函数参数中不存在潜在的歧义,那么构造函数参数在bean定义(文件)中定义的顺序就是实例化bean时将这些参数提供给适当的构造函数的顺序。【完美机翻】
Consider the following class:
考虑以下的类:
Java
package x.y;
public class ThingOne {
public ThingOne(ThingTwo thingTwo, ThingThree thingThree) {
// ...
}
}
Kotlin
package x.y
class ThingOne(thingTwo: ThingTwo, thingThree: ThingThree)
Assuming that ThingTwo and ThingThree classes are not related by inheritance, no potential ambiguity exists.
假设ThingTwo和ThingThree类与继承无关,没有潜在的歧义。
Thus, the following configuration works fine, and you do not need to specify the
constructor argument indexes or types explicitly in the <constructor-arg/> element.
这样,下面的配置就会正常工作以及你不需要在<constructor-arg/>元素明确地指定构造参数的索引或类型。
<beans>
<bean id="beanOne" class="x.y.ThingOne">
<constructor-arg ref="beanTwo"/>
<constructor-arg ref="beanThree"/>
</bean>
<bean id="beanTwo" class="x.y.ThingTwo"/>
<bean id="beanThree" class="x.y.ThingThree"/>
</beans>
When another bean is referenced, the type is known, and matching can occur (as
was the case with the preceding example).
当其他bean被引用,其类型已知,且可以被匹配(就像前面的例子一样)。
When a simple type is used, such as <value>true</value>, Spring cannot determine the type of the value, and so cannot match by type without help.
当一个简单类型被使用过,例如<value>true</value>,Spring不可以确定其value的类型,所以根据类型匹配就没有用了。
Consider the following class:
考虑下面的类: