自动装配的四种模式
Spring 为自动装配提供了四种注入模式(注意是自动装配注入模式,不是注入形式),分别是 NO、BY_NAME、BY_TYPE 和 Constructor。
Spring 对这四种注入模式的描述如下
| Mode | Explanation |
|---|---|
| no | (Default) No autowiring. Bean references must be defined by ref elements. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system. |
| byName | Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master and uses it to set the property. |
| byType | Lets a property be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens (the property is not set). |
| constructor | Analogous to byType but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. |
另外,这个四种注入模式在接口类 AutowireCapableBeanFactory 中也有定义,如下:
public interface AutowireCapableBeanFactory extends BeanFactory {
int AUTOWIRE_NO = 0;
int AUTOWIRE_BY_NAME = 1;
int AUTOWIRE_BY_TYPE = 2;
int AUTOWIRE_CONSTRUCTOR = 3;
@Deprecated
int AUTOWIRE_AUTODETECT = 4;
// omitted...
}
不过有趣的是另一个枚举类 Autowire(如下),这个枚举类与 @Autowired 注解有些关系。你会发现在这个枚举类中没有定义 Constructor 注入模式,这在之后的文章中慢慢的说。
public enum Autowire {
NO(AutowireCapableBeanFactory.AUTOWIRE_NO),
BY_NAME(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME),
BY_TYPE(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE);
private final int value;
Autowire(int value) {
this.value = value;
}
public int value() {
return this.value;
}
public boolean isAutowire() {
return (this == BY_NAME || this == BY_TYPE);
}
}