在AbstractAutowireCapableBeanFactory的createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) 的方法中,
获取新实例BeanWrapper有四种方式:

  • obtainFromSupplier回调方式
    没有用到InstantiationStrategy
  • instantiateUsingFactoryMethod工厂方法方式
    使用了InstantiationStrategy中的instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
    @Nullable Object factoryBean, Method factoryMethod, Object… args)
  • autowireConstructor自动注入方式
    使用了InstantiationStrategy中的instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
    Constructor<?> ctor, Object… args)
  • instantiateBean默认构造函数方式
    使用了InstantiationStrategy中的instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)

1、InstantiationStrategy接口

负责创建与root bean definition对应的实例。 这是一种策略,因为各种方法都是可能的,包括使用CGLIB动态创建子类来支持方法注入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface InstantiationStrategy {
//在此工厂中返回具有给定名称的bean实例。
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)
throws BeansException;
//在这个工厂中返回具有给定名称的bean实例,并通过给定的构造函数创建它。
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
Constructor<?> ctor, Object... args) throws BeansException;
//在此工厂中返回具有给定名称的bean实例,并通过给定的工厂方法创建它。
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
@Nullable Object factoryBean, Method factoryMethod, Object... args)
throws BeansException;

}

下面逐个分析这个接口的实现类SimpleInstantiationStrategy中的方法实现。

1.1、instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)

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
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// 如果没有覆盖,不要使用CGLIB覆盖该类。
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
//构造函数锁
synchronized (bd.constructorArgumentLock) {
//解析构造方法
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
//如果没有构造方法
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
//指定的类是一个接口
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
//从clazz中获取方法:getDeclaredConstructor包括私有方法
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
//通过反射获取对象
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// 必须生成CGLIB子类。Method Injection not supported in SimpleInstantiationStrategy
// CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy
return instantiateWithMethodInjection(bd, beanName, owner);
}
}

1.2、instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,final Constructor<?> ctor, Object… args)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
final Constructor<?> ctor, Object... args) {
// 如果没有覆盖,不要使用CGLIB覆盖该类。
if (!bd.hasMethodOverrides()) {
if (System.getSecurityManager() != null) {
// use own privileged to change accessibility (when security is on)
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(ctor);
return null;
});
}
//通过反射获取对象
return BeanUtils.instantiateClass(ctor, args);
}
else {
//CGLIB
return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
}
}

1.3、instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,

        @Nullable Object factoryBean, final Method factoryMethod, Object... args)
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
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
@Nullable Object factoryBean, final Method factoryMethod, Object... args) {

try {
//安全管理器
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(factoryMethod);
return null;
});
}
else {
ReflectionUtils.makeAccessible(factoryMethod);
}

//从ThreadLocal中获取先前调用的工厂方法
Method priorInvokedFactoryMethod = currentlyInvokedFactoryMethod.get();
try {
//工厂方法塞到ThreadLocal
currentlyInvokedFactoryMethod.set(factoryMethod);
// 反射
Object result = factoryMethod.invoke(factoryBean, args);
if (result == null) {
result = new NullBean();
}
return result;
}
finally {
if (priorInvokedFactoryMethod != null) {
currentlyInvokedFactoryMethod.set(priorInvokedFactoryMethod);
}
else {
currentlyInvokedFactoryMethod.remove();
}
}
}
//各种catch

catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(factoryMethod,
"Illegal arguments to factory method '" + factoryMethod.getName() + "'; " +
"args: " + StringUtils.arrayToCommaDelimitedString(args), ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(factoryMethod,
"Cannot access factory method '" + factoryMethod.getName() + "'; is it public?", ex);
}
catch (InvocationTargetException ex) {
String msg = "Factory method '" + factoryMethod.getName() + "' threw exception";
if (bd.getFactoryBeanName() != null && owner instanceof ConfigurableBeanFactory &&
((ConfigurableBeanFactory) owner).isCurrentlyInCreation(bd.getFactoryBeanName())) {
msg = "Circular reference involving containing bean '" + bd.getFactoryBeanName() + "' - consider " +
"declaring the factory method as static for independence from its containing instance. " + msg;
}
throw new BeanInstantiationException(factoryMethod, msg, ex.getTargetException());
}
}

可以看出上面几个方法可以看出,spring实例化bean,主要用了java反射与CGLIB。

tencent.jpg