服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - Spring bean的实例化和IOC依赖注入详解

Spring bean的实例化和IOC依赖注入详解

2021-07-22 15:37清幽之地 Java教程

这篇文章主要介绍了Spring bean的实例化和IOC依赖注入详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

前言

我们知道,ioc是spring的核心。它来负责控制对象的生命周期和对象间的关系。

举个例子,我们如何来找对象的呢?常见的情况是,在路上要到处去看哪个mm既漂亮身材又好,符合我们的口味。就打听她们的电话号码,制造关联想办法认识她们,然后...这里省略n步,最后谈恋爱结婚。

ioc在这里就像婚介所,里面有很多适婚男女的资料,如果你有需求,直接告诉它你需要个什么样的女朋友就好了。它会给我们提供一个mm,直接谈恋爱结婚,完美!

下面就来看spring是如何生成并管理这些对象的呢?

1、方法入口
org.springframework.beans.factory.support.defaultlistablebeanfactory.preinstantiatesingletons()方法是今天的主角,一切从它开始。

?
1
2
3
4
5
6
7
8
9
10
11
public void preinstantiatesingletons() throws beansexception {
   //beandefinitionnames就是上一节初始化完成后的所有beandefinition的beanname
   list<string> beannames = new arraylist<string>(this.beandefinitionnames);
   for (string beanname : beannames) {
     rootbeandefinition bd = getmergedlocalbeandefinition(beanname);
     if (!bd.isabstract() && bd.issingleton() && !bd.islazyinit()) {
       //getbean是主力中的主力,负责实例化bean和ioc依赖注入
       getbean(beanname);
     }
   }
 }

2、bean的实例化

在入口方法getbean中,首先调用了docreatebean方法。第一步就是通过反射实例化一个bean。

?
1
2
3
4
5
6
7
8
9
10
11
protected object docreatebean(final string beanname, final rootbeandefinition mbd, final object[] args) {
  // instantiate the bean.
  beanwrapper instancewrapper = null;
  if (mbd.issingleton()) {
    instancewrapper = this.factorybeaninstancecache.remove(beanname);
  }
  if (instancewrapper == null) {
    //createbeaninstance就是实例化bean的过程,无非就是一些判断加反射,最后调用ctor.newinstance(args);
    instancewrapper = createbeaninstance(beanname, mbd, args);
  }
}

3、annotation的支持

在bean实例化完成之后,会进入一段后置处理器的代码。从代码上看,过滤实现了mergedbeandefinitionpostprocessor接口的类,调用其postprocessmergedbeandefinition()方法。都是谁实现了mergedbeandefinitionpostprocessor接口呢?我们重点看三个

  • autowiredannotationbeanpostprocessor
  • commonannotationbeanpostprocessor
  • requiredannotationbeanpostprocessor

记不记得在spring源码分析(一)spring的初始化和xml这一章节中,我们说spring对annotation-config标签的支持,注册了一些特殊的bean,正好就包含上面这三个。下面来看它们偷偷做了什么呢?

从方法名字来看,它们做了相同一件事,加载注解元数据。方法内部又做了相同的两件事

?
1
2
reflectionutils.dowithlocalfields(targetclass, new reflectionutils.fieldcallback()
reflectionutils.dowithlocalmethods(targetclass, new reflectionutils.methodcallback()

看方法的参数,targetclass就是bean的class对象。接下来就可以获取它的字段和方法,判断是否包含了相应的注解,最后转成injectionmetadata对象,下面以一段伪代码展示处理过程。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void main(string[] args) throws classnotfoundexception {
  class<?> clazz = class.forname("com.viewscenes.netsupervisor.entity.user");
  field[] fields = clazz.getfields();
  method[] methods = clazz.getmethods();
 
  for (int i = 0; i < fields.length; i++) {
    field field = fields[i];
    if (field.isannotationpresent(autowired.class)) {
      //转换成autowiredfieldelement对象,加入容器
    }
  }
  for (int i = 0; i < methods.length; i++) {
    method method = methods[i];
    if (method.isannotationpresent(autowired.class)) {
      //转换成autowiredmethodelement对象,加入容器
    }
  }
  return new injectionmetadata(clazz, elements);
}

injectionmetadata对象有两个重要的属性:targetclass ,injectedelements,在注解式的依赖注入的时候重点就靠它们。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
public injectionmetadata(class<?> targetclass, collection<injectedelement> elements) {
  //targetclass是bean的class对象
  this.targetclass = targetclass;
  //injectedelements是一个injectedelement对象的集合
  this.injectedelements = elements;
}
//member是成员本身,字段或者方法
//pd是jdk中的内省机制对象,后面的注入属性值要用到
protected injectedelement(member member, propertydescriptor pd) {
  this.member = member;
  this.isfield = (member instanceof field);
  this.pd = pd;
}

说了这么多,最后再看下源码里面是什么样的,以autowired 为例。

?
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
reflectionutils.dowithlocalfields(targetclass, new reflectionutils.fieldcallback() {
  @override
  public void dowith(field field) throws illegalargumentexception, illegalaccessexception {
    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;
      }
      boolean required = determinerequiredstatus(ann);
      currelements.add(new autowiredfieldelement(field, required));
    }
  }
});
 
reflectionutils.dowithlocalmethods(targetclass, new reflectionutils.methodcallback() {
  @override
  public void dowith(method method) throws illegalargumentexception, illegalaccessexception {
    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.getparametertypes().length == 0) {
        if (logger.iswarnenabled()) {
          logger.warn("autowired annotation should be used on methods with parameters: " + method);
        }
      }
      boolean required = determinerequiredstatus(ann);
      propertydescriptor pd = beanutils.findpropertyformethod(bridgedmethod, clazz);
      currelements.add(new autowiredmethodelement(method, required, pd));
    }
  }
});

4、依赖注入

前面完成了在docreatebean()方法bean的实例化,接下来就是依赖注入。

bean的依赖注入有两种方式,一种是配置文件,一种是注解式。

4.1、 注解式的注入过程

在上面第3小节,spring已经过滤了bean实例上包含@autowired、@resource等注解的field和method,并返回了包含class对象、内省对象、成员的injectionmetadata对象。还是以@autowired为例,这次调用到autowiredannotationbeanpostprocessor.postprocesspropertyvalues()。

首先拿到injectionmetadata对象,再判断里面的injectedelement集合是否为空,也就是说判断在bean的字段和方法上是否包含@autowired。然后调用injectedelement.inject()。injectedelement有两个子类autowiredfieldelement、autowiredmethodelement,很显然一个是处理field,一个是处理method。

4.1.1 autowiredfieldelement

如果autowired注解在字段上,它的配置是这样。

?
1
2
3
4
public class user {
  @autowired
  role role;
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected void inject(object bean, string beanname, propertyvalues pvs) throws throwable {
  //以user类中的@autowired role role为例,这里的field就是
  //public com.viewscenes.netsupervisor.entity.role com.viewscenes.netsupervisor.entity.user.role
  field field = (field) this.member;
  object value;
  dependencydescriptor desc = new dependencydescriptor(field, this.required);
  desc.setcontainingclass(bean.getclass());
  set<string> autowiredbeannames = new linkedhashset<string>(1);
  typeconverter typeconverter = beanfactory.gettypeconverter();
  try {
    //这里的beanname因为bean,所以会重新进入populatebean方法,先完成role对象的注入
    //value == com.viewscenes.netsupervisor.entity.role@7228c85c
    value = beanfactory.resolvedependency(desc, beanname, autowiredbeannames, typeconverter);
  }
  catch (beansexception ex) {
    throw new unsatisfieddependencyexception(null, beanname, new injectionpoint(field), ex);
  }
  if (value != null) {
    //设置可访问,直接赋值
    reflectionutils.makeaccessible(field);
    field.set(bean, value);
  }
}

4.1.2 autowiredfieldelement

如果autowired注解在方法上,就得这样写。

?
1
2
3
4
public class user {
  @autowired
  public void setrole(role role) {}
}

它的inject方法和上面类似,不过最后是method.invoke。感兴趣的小伙伴可以去翻翻源码。

?
1
2
reflectionutils.makeaccessible(method);
method.invoke(bean, arguments);

4.2、配置文件的注入过程

先来看一个配置文件,我们在user类中注入了id,name,age和role的实例。

?
1
2
3
4
5
6
7
8
9
10
<bean id="user" class="com.viewscenes.netsupervisor.entity.user">
  <property name="id" value="1001"></property>
  <property name="name" value="网机动车"></property>
  <property name="age" value="24"></property>
  <property name="role" ref="role"></property>
</bean>
<bean id="role" class="com.viewscenes.netsupervisor.entity.role">
  <property name="id" value="1002"></property>
  <property name="name" value="中心管理员"></property>
</bean>

spring源码分析(一)spring的初始化和xml这一章节的4.2 小节,bean标签的解析,我们看到在反射得到bean的class对象后,会设置它的property属性,也就是调用了parsepropertyelements()方法。在beandefinition对象里有个mutablepropertyvalues属性。

?
1
2
3
4
5
6
7
8
9
mutablepropertyvalues:
 //propertyvaluelist就是有几个property 节点
 list<propertyvalue> propertyvaluelist:
  propertyvalue:
   name   //对应配置文件中的name  ==id
   value   //对应配置文件中的value ==1001
  propertyvalue:
   name   //对应配置文件中的name  ==name
   value   //对应配置文件中的value ==网机动车

上图就是beandefinition对象里面mutablepropertyvalues属性的结构。既然已经拿到了property的名称和值,注入就比较简单了。从内省对象propertydescriptor中拿到writemethod对象,设置可访问,invoke即可。propertydescriptor有两个对象readmethodref、writemethodref其实对应的就是get set方法。

?
1
2
3
4
5
6
7
8
public void setvalue(final object object, object valuetoapply) throws exception {
  //pd 是内省对象propertydescriptor
  final method writemethod = this.pd.getwritemethod());
  writemethod.setaccessible(true);
  final object value = valuetoapply;
  //以id为例 writemethod == public void com.viewscenes.netsupervisor.entity.user.setid(java.lang.string)
  writemethod.invoke(getwrappedinstance(), value);
}

5、initializebean
在bean实例化和ioc依赖注入后,spring留出了扩展,可以让我们对bean做一些初始化的工作。

5.1、aware

aware是一个空的接口,什么也没有。不过有很多xxxaware继承自它,下面来看源码。如果有需要,我们的bean可以实现下面的接口拿到我们想要的。

?
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
//在实例化和ioc依赖注入完成后调用
  private void invokeawaremethods(final string beanname, final object bean) {
  if (bean instanceof aware) {
    //让我们的bean可以拿到自身在容器中的beanname
    if (bean instanceof beannameaware) {
      ((beannameaware) bean).setbeanname(beanname);
    }
    //可以拿到classloader对象
    if (bean instanceof beanclassloaderaware) {
      ((beanclassloaderaware) bean).setbeanclassloader(getbeanclassloader());
    }
    //可以拿到beanfactory对象
    if (bean instanceof beanfactoryaware) {
      ((beanfactoryaware) bean).setbeanfactory(abstractautowirecapablebeanfactory.this);
    }
    if (bean instanceof environmentaware) {
      ((environmentaware) bean).setenvironment(this.applicationcontext.getenvironment());
    }
    if (bean instanceof embeddedvalueresolveraware) {
      ((embeddedvalueresolveraware) bean).setembeddedvalueresolver(this.embeddedvalueresolver);
    }
    if (bean instanceof resourceloaderaware) {
      ((resourceloaderaware) bean).setresourceloader(this.applicationcontext);
    }
    if (bean instanceof applicationeventpublisheraware) {
      ((applicationeventpublisheraware) bean).setapplicationeventpublisher(this.applicationcontext);
    }
    if (bean instanceof messagesourceaware) {
      ((messagesourceaware) bean).setmessagesource(this.applicationcontext);
    }
    if (bean instanceof applicationcontextaware) {
      ((applicationcontextaware) bean).setapplicationcontext(this.applicationcontext);
    }
    ......未完
  }
}

做法如下:

?
1
2
3
4
5
6
7
8
9
10
11
public class awaretest1 implements beannameaware,beanclassloaderaware,beanfactoryaware{
  public void setbeanname(string name) {
    system.out.println("beannameaware:" + name);
  }
  public void setbeanfactory(beanfactory beanfactory) throws beansexception {
    system.out.println("beanfactoryaware:" + beanfactory);
  }
  public void setbeanclassloader(classloader classloader) {
    system.out.println("beanclassloaderaware:" + classloader);
  }
}

//输出结果
beannameaware:awaretest1
beanclassloaderaware:webappclassloader
  context: /springmvc_dubbo_producer
  delegate: false
  repositories:
    /web-inf/classes/
----------> parent classloader:
java.net.urlclassloader@2626b418
beanfactoryaware:org.springframework.beans.factory.support.defaultlistablebeanfactory@5b4686b4: defining beans ...未完

5.2、初始化

bean的初始化方法有三种方式,按照先后顺序是,@postconstruct、afterpropertiesset、init-method

5.2.1 @postconstruct

这个注解隐藏的比较深,它是在commonannotationbeanpostprocessor的父类initdestroyannotationbeanpostprocessor调用到的。这个注解的初始化方法不支持带参数,会直接抛异常。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if (method.getparametertypes().length != 0) {
  throw new illegalstateexception("lifecycle method annotation requires a no-arg method: " + method);
}
public void invoke(object target) throws throwable {
  reflectionutils.makeaccessible(this.method);
  this.method.invoke(target, (object[]) null);
}
 
5.2.2 afterpropertiesset
这个要实现initializingbean接口。这个也不能有参数,因为它接口方法就没有定义参数。
  boolean isinitializingbean = (bean instanceof initializingbean);
  if (isinitializingbean && (mbd == null || !mbd.isexternallymanagedinitmethod("afterpropertiesset"))) {
    if (logger.isdebugenabled()) {
      logger.debug("invoking afterpropertiesset() on bean with name '" + beanname + "'");
    }
    ((initializingbean) bean).afterpropertiesset();
  }

5.2.3 init-method

?
1
2
reflectionutils.makeaccessible(initmethod);
initmethod.invoke(bean);

6、注册

registerdisposablebeanifnecessary()完成bean的缓存注册工作,把bean注册到map中。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.jianshu.com/p/00f1a6739a9e

延伸 · 阅读

精彩推荐