使用Spring开发时,主要有两种配置方式,一种是 xml的方式,一种是java config的方式。
Spring技术本身也在不断发展和变化。在使用的过程中,我们难免会遇到各种处理注解的情况,其中我们使用最多的应该就是@Autowired注解了。这个注解的作用就是为我们注入一个定义的bean。
那么,除了我们常用的属性注入方式之外,还有哪些方式可以使用这个注解呢?在代码层面是如何实现的呢?这是本文所关注的问题。
如何使用@Autowired注解?
将@Autowired注解应用到构造函数,如以下示例所示:
@Component
public class BeanConfig{
@Autowired
private BeanConfig beanConfig;
@Autowired
private void setBeanConfig(BeanConfig beanConfig) {
this.beanConfig = beanConfig;
}
}
直接应用于字段是我们使用最多的方式,但是从代码层面使用构造函数注入会更好。
此外,还有以下几种不太常见的方法。
@Autowired
private List<BeanConfig> beanConfigList;
@Autowired
private Set<BeanConfig> beanConfigSet;
@Autowired
私有Map<String, BeanConfig> beanConfigMap;
虽然我们经常使用这个注解,但是我们真的知道它的作用吗?
首先,从它的作用范围来看,其实这个注解是属于Spring容器配置的注解,还有其他的属于容器配置的注解:@Required, @Primary, @Qualifier等等。
其次,我们可以直接看字面意思,autowire,这个词的意思就是自动装配的意思。
自动装配是什么意思?该术语的本义是指在某些行业中利用机器来代替人口,自动完成一些需要完成的装配任务,或者完成其他任务。
在spring的世界里,自动组装是指使用Spring容器中的bean与我们需要这个bean的类自动组装起来。这个注解的作用的定义是:自动将Spring容器中的bean与我们需要这个bean一起使用的类组装起来。
接下来我们看看这个注解背后的工作。
如何实现@Autowired注解?
Java注解实现的核心技术是反射。让我们通过一些例子和自己实现一个注解来理解它的工作原理。
我们拿到目标之后就可以用反射来给他实现一个逻辑。这种逻辑超出了这些方法本身的逻辑。我们可以想到proxy、aop等知识。我们相当于对这些方法做了一个逻辑的增强。
其实注解实现的主要逻辑大概就是这个思路。总结一下大致步骤如下:
- 利用反射机制获取某个类的Class对象。
- 通过这个类对象,可以获取它的每一个method方法,或者字段等。
- Method、Field等类提供了类似getAnnotation的方法来获取某个字段的所有注解。
- 拿到注解后,我们可以判断该注解是否是我们要实现的注解,如果是,则实现注解逻辑。
现在我们来实现这个逻辑,代码如下:
public void postProcessProperties () throws Exception {
Class<BeanConfig> beanConfigClass = BeanConfig.class; }
BeanConfig instance = beanConfigClass.newInstance();
Field[] fields = beanConfigClass.getDeclaredFields();
for (Field field : fields) {
// getAnnotation,判断是否有Autowired
Autowired autowired = field.getDeclaredAnnotation(Autowired.class);
if (autowired != null ) {
String fileName = field.getName();
Class<?> declaringClass = field.getDeclaringClass();
Object bean = new Object ();
field.setAccessible( true );
field.set(bean, instance);
} }
}
从上面的实现逻辑我们不难发现,借助Java反射,我们可以直接获取一个类中的所有方法,然后获取方法上的注解。当然,我们也可以获取字段上的注解。
借助反射,我们几乎可以获得属于某个类的任何内容。
这样一个简单的注解我们就完成了。
知道了上面的知识,我们不难想到,上面的注解虽然简单,但是@Autowired和他最大的区别应该只是注解的实现逻辑,其他的步骤比如使用反射获取注解等应该是相同的。
我们看一下spring源码中@Autowired注解是如何定义的,如下所示。
package org.springframework.beans.factory.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
阅读代码,我们可以看到Autowired注解可以应用于五种类型的构造方法、普通方法、参数、字段和注解,其保留策略是在运行时。
接下来我们看一下spring对这个注解的逻辑实现。
在Spring源码中,Autowired注解位于org.springframework.beans.factory.annotation包
经过分析不难发现Spring对于autowire注解的实现逻辑位于类:AutowiredAnnotationBeanPostProcessor。
源码分析。
核心处理代码如下:
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>();
// 需要处理的目标类
Class<?> targetClass = clazz;
do {
final LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>();
// 通过反射获取该类的所有字段,并遍历各个字段
// 通过findAutowiredAnnotation方法遍历各个字段使用的注解
// 如果使用autowired修改,则返回autowired相关属性
ReflectionUtils.doWithLocalFields(targetClass, field -> {
AnnotationAttributes ann = findAutowiredAnnotation(field);
// Check whether the autowired annotation is used on the static method
if (ann != null) {
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static fields: " + field);
}
return;
}
//判断是否指定了required
boolean required = determineRequiredStatus(ann);
currElements.add(new AutowiredFieldElement(field, required));
}
});
// 和上面的逻辑一样,只不过是通过反射处理类的方法 ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static methods: " + method);
}
return;
}
if (method.getParameterCount() == 0) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation should only be used on methods with parameters: " +
method);
}
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new AutowiredMethodElement(method, required, pd));
}
});
// 可能有多个用@Autowired修改的注解
// 因此,它们都被添加到 currElements 容器中并一起处理elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
return new InjectionMetadata(clazz, elements);
}
最后,该方法返回一个InjectionMetadata包含所有autowire注解的集合。
这个类由两部分组成。
public InjectionMetadata(Class<?> targetClass, Collection<InjectedElement> elements) {
this.targetClass = targetClass;
this.injectedElements = elements;
}
一个是我们正在处理的目标类,另一个是上面方法得到的集合elements。
有了目标类和所有需要注入的元素,我们就可以实现自动装配的依赖注入逻辑。实现方法如下。
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
}
它调用的方法是inject中定义的方法InjectionMetadata。
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Collection<InjectedElement> checkedElements = this.checkedElements;
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
for (InjectedElement element : elementsToIterate) {
if (logger.isTraceEnabled()) {
logger.trace("Processing injected element of bean '" + beanName + "': " + element);
}
element.inject(target, beanName, pvs);
}
}
}
/**
* Either this or {@link #getResourceToInject} needs to be overridden.
*/
protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
throws Throwable {
if (this.isField) {
Field field = (Field) this.member;
ReflectionUtils.makeAccessible(field);
field.set(target, getResourceToInject(target, requestingBeanName));
}
else {
if (checkPropertySkipping(pvs)) {
return;
}
try {
Method method = (Method) this.member;
ReflectionUtils.makeAccessible(method);
method.invoke(target, getResourceToInject(target, requestingBeanName));
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
以上就是@Autowire注解实现逻辑的完整分析。
下面是spring容器实现@AutoWired自动注入的时序图。