Spring Bean的实例化

Bean的实例化

构造器的选择

SimpleInstantiationStrategy

Bean实例化有两种策略,一种是CGLIB,另一种是通过 BeanUtil,即用JVM反射生成对象。
如果Bean中有 @LookUp注解,或者xml中指定了 lookup-method,那么就会采用CGLIB来实例化对象,因为需要重写 @LookUp标记的方法,这种情况下很容易想到使用代理,使用代理,被代理类又不需实现接口,无疑CGLB方式合适。
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
   // Don't override the class with CGLIB if no overrides.
 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");
 }
 //获取无参构造器去实例化Bean
            try {
               if (System.getSecurityManager() != null) {
                  constructorToUse = AccessController.doPrivileged(
                        (PrivilegedExceptionAction>) clazz::getDeclaredConstructor);
 }
               else {
                  constructorToUse = clazz.getDeclaredConstructor();
 }
               bd.resolvedConstructorOrFactoryMethod = constructorToUse;
 }
            catch (Throwable ex) {
               throw new BeanInstantiationException(clazz, "No default constructor found", ex);
 }
         }
      }
      // 通过JVM反射功能生成实例化对象
      return BeanUtils.instantiateClass(constructorToUse);
 }
   else {
      // 通过CGLIB来生成实例化对象
 return instantiateWithMethodInjection(bd, beanName, owner);
 }
}

你可能感兴趣的:(java)