@Component
public class BeanConfig{
@Autowired
private BeanConfig beanConfig;
@Autowired
public BeanConfig(BeanConfig beanConfig){
this.beanConfig= beanConfig;}}
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);// 检查静态方法上是否使用了自动装配注解
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);}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
最后,此方法返回一个InjectionMetadata包含所有autowire注解的集合。
这个类由两部分组成:
public InjectionMetadata(Class<?> targetClass, Collection<InjectedElement> elements){
this.targetClass= targetClass;
this.injectedElements= elements;}