Spring源码分析

259 阅读11分钟

Spring源码分析

一、定义Bean的方式

1.JavaBean 和 SpringBean 以及对象的区别

Bean就是对象

对象

User user = new User();

user.name

JavaBean:实际就是get/set

User user = new User();

user.getname   //私有化属性,对外提供get/set

SpringBean

//编写xml文件,配置bean
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("xml");
User user = context.getBean("user");
//spring容器帮我们生成的对象————> spring bean

2.声明式:定义Bean的方式

Bean 标签

<bean id="user" class="com.study.User">

@Bean 注解

//省去了写xml,更加灵活
@Bean
public User user(){
  return new User();
}
//main方法
ApplicationContext context = new AnnotationConfigApplicationContext(config.class);
User user = context.getBean("user");

@component

@component 注解标注的类,相当于把这个类当成bean,spring会自己将类注册

3.编程式:定义Bean的方式BeanDefinition

//BeanDefinition 就是bean在spring中的描述
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//先构建一个beanDefinition对象:bean描述类的对象
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition()
  																													 .getBeanDefinition();
//设置信息
beanDefinition.setBeanClass(User.class);
context.registerBeanDefinition("user",beanDefinition);
context.refresh();
User user = context.getBean("user",User.class);

4.定义Bean的方式FactoryBean

//定义一个类
public class Person{
 	//set
  //get
}

//再定义一个类
public class TestFactoryBean implements FactoryBean{
    @Override
    public Object getObject() throws Exception {
        //这个Bean是我们自己new的,这里我们就可以控制Bean的创建过程了
        return new Person();
    }

    @Override
    public Class<?> getObjectType() {
        return Person.class;
    }
}

//BeanDefinition 就是bean在spring中的描述
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//先构建一个beanDefinition对象:bean描述类的对象
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition()
  																													 .getBeanDefinition();
//设置信息
beanDefinition.setBeanClass(TestFactoryBean.class); //实际加载了两个bean对象
context.registerBeanDefinition("user",beanDefinition);
context.refresh();
//产生了两个对象
Person bean = context.getBean("user",Person.class);
TestFactoryBean bean2 = context.getBean("&user",TestFactoryBean.class);

5.Supplier定义bean的方式

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.registerBean(Person.class,new Supplier<Person>(){//把这个类注册成bean
  @Override
  public Person get(){
    Person person = new Person();
    person.setname("aaa");
    return person;
  }
});
context.refresh();
Person bean = context.getBean("person",Person.class);//名字默认为类的小写

二、Spring容器里面到底是什么?

1.单例池

application.registerBean(User.class); // 单例Bean
//是不是spring容器里面只能有一个User类型的Bean:错

单例池:ConcurreentHashMap

Key: singletonObject beanName

Value: Object

原型(多例)
<bean id="user" class="com.study.User",scope="prototype"/>

默认单例
<bean id="user1" class="com.study.User"/>

2.BeanFactory

顾名思义:生产bean的

//Bean工厂
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
//在工厂里去注册这个bean
beanFactory.registerSingleton("user",new User());
//获取bean
User user = beanFactory.getBean("user", User.class);

3.ApplicationContext

其实ApplicationContext 继承于 BeanFactory

ApplicationContext功能十分强大

1.获取一些资源

2.国际化设置

3.发布事件

3.1ClassPathXmlApplicationContext

//查找的路径是class下,编译后的文件夹
ClassPathXmlApplicationContext Ccontext = new ClassPathXmlApplicationContext("spring.xml");
//查找的是相对工程的目录下
FileSystemXmlApplicationContext Fcontext = new FileSystemXmlApplicationContext("src/main/resources/spring.xml");

3.2AnnotationConfigApplicationContext

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

4.可刷新与不可刷新

context.refresh();

//ClassPathXmlApplicationContext 支持刷新
//AnnotationConfigApplicationContext 不支持刷新

三、Bean的生命周期

1.Bean生命周期创建过程简述

1⃣️生成BeanDefinition

BeanDefinition 是 Bean的定义,Spring根据BeanDefinition 来创建bean 对象

//BeanDefinition 核心属性
beanClass:一个bean的类型,例:UserService.class
private volatile Object beanClass;

scope:表示一个bean的作用域
private String scope;
		String SCOPE_SINGLETON = "singleton"; //单例
    String SCOPE_PROTOTYPE = "prototype"; //原型

isLazy:表示一个bean是否需要懒加载
  	//原型bean中,isLazy属性不起作用
  	//懒加载的单例bean,会在第一个getBean的时候生成该bean
  	//非懒加载的单例bean,则会在spring启动过程中直接生成好
  
dependsOn:表示一个bean创建之前所依赖的其他bean,依赖的bean必须先创建好
private String[] dependsOn;

primary:表示一个bean是主bean,在Spring中一个类型可以有多个bean,在进行注入的时候,如果根据类型找到了多个bean,则会判断这些bean中是否存在主bean,若存在,则直接给主bean注入属性
private boolean primary;

initMethodName:表示一个bean的初始化方法,一个bean的生命周期过程在初始化会去调用bean的初始化方法,初始化逻辑可以有程序员自己定义
private String initMethodName;

2⃣️合并BeanDefinition

阅读源码

protected RootBeanDefinition getMergedBeanDefinition(
		String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
		throws BeanDefinitionStoreException {

	synchronized (this.mergedBeanDefinitions) {
		// 创建一个RootBeanDefinition对象,用来存放合并后的bd
		RootBeanDefinition mbd = null;

		// Check with full lock now in order to enforce the same merged instance.
		if (containingBd == null) {
			mbd = this.mergedBeanDefinitions.get(beanName);
		}

		if (mbd == null) {
			// 如果不存在父bd那么就直接由本身克隆出一个RootBeanDefinition
			if (bd.getParentName() == null) {
				// Use copy of given root bean definition.
				if (bd instanceof RootBeanDefinition) {
					mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
				}
				else {
					mbd = new RootBeanDefinition(bd);
				}
			}
			// 如果存在父bd
			else {
				// Child bean definition: needs to be merged with parent.
				BeanDefinition pbd;
				try {
					// 如果父bd也有父bd那么就先通过getMergedBeanDefinition方法得到合并后的父bd对象
					String parentBeanName = transformedBeanName(bd.getParentName());
					if (!beanName.equals(parentBeanName)) {
						pbd = getMergedBeanDefinition(parentBeanName);
					}
					else {
						BeanFactory parent = getParentBeanFactory();
						if (parent instanceof ConfigurableBeanFactory) {
							pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
						}
						else {
							throw new NoSuchBeanDefinitionException(parentBeanName,
									"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
									"': cannot be resolved without an AbstractBeanFactory parent");
						}
					}
				}
				catch (NoSuchBeanDefinitionException ex) {
					throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
							"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
				}
				// Deep copy with overridden values.
				// 由父bd创建出一个RootBeanDefinition对象
				mbd = new RootBeanDefinition(pbd);
				// 子bd覆盖父bd(覆盖属性之类的)
				mbd.overrideFrom(bd);
			}

			// Set default singleton scope, if not configured before.
			if (!StringUtils.hasLength(mbd.getScope())) {
				mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
			}
			if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
				mbd.setScope(containingBd.getScope());
			}
			if (containingBd == null && isCacheBeanMetadata()) {
				// 最后将合并后的bd放入mergedBeanDefinitions集合中
				this.mergedBeanDefinitions.put(beanName, mbd);
			}
		}

		return mbd;
	}
}
  • 找到父bd,如果没有找到就直接将自身当作父bd,找到的话就看看父bd有没有父bd,并且通过getMergedBeanDefinition方法得到父bd合并之后的bd。
  • 合并bd,通过父bd创建出一个RootBeanDefinition对象,然后子bd覆盖父bd创建出来的对象(覆盖属性之类的)。
  • 将合并后的bd放入一个mergedBeanDefinitions集合中,最后将合并后的bd返回。

3⃣️类的加载

类加载器--> 类加载过程--> 双亲委派机制

4⃣️实例化前

借助于InstantiationAwareBeanPostProcessor

@Component
public class MyBeanPostProcess implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if(beanName.equals("user")) {
            System.out.println("实例化前");
        }
        return null;
    }
}


public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
        User user = applicationContext.getBean("user", User.class);
        System.out.println(user);
    }
}

image.png 5⃣️推断构造方法 和 实例化

  • 如果想要执行指定的构造方法,则可以加**@Autowired**注解
@Component
public class UserService {

    private User user;

    public UserService(){
        System.out.println("无参构造");
    }

    @Autowired
    public UserService(User user){
        this.user = user;
        System.out.println("一个参数的有参构造");
    }

    public UserService(User user,User user1){
        this.user = user;
        System.out.println("二个参数的有参构造");
    }
}

6⃣️实例化后

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if(beanName.equals("userService")){
            System.out.println("实例化后");
        }
        return true;
    }

image.png 7⃣️BeanDefinition的后置处理

Bean的后置处理器:BeanPostProcess

- 实现BeanPostProcessor接口
	- postProcessBeforeInitialization方法
	- postProcessAfterInitialization方法
  

@Component
public class MyLastBeanPostProcess implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("userService")) {
            System.out.println("初始化前");
        }
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("userService")) {
            System.out.println("初始化后");
        }
        return null;
    }
}

8⃣️依赖注入

9⃣️执行Aware

🔟初始化

实现InitializingBean 接口

@Component
public class UserService implements InitializingBean {

    private User user;

    public UserService(){
        System.out.println("无参构造");
    }

    @Autowired
    public void setUser(User user) {
        System.out.println("set注入");
        this.user = user;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化");
    }
}

如果你不需要在初始化前后对bean进行操作,则可以实现此接口

2.Bean生命周期消亡过程简述

bean的销毁实现的是DisposableBean 接口

@Component
public class UserService implements InitializingBean, DisposableBean {

    private User user;

    public UserService(){
        System.out.println("无参构造");
    }

    @Autowired
    public void setUser(User user) {
        System.out.println("set注入");
        this.user = user;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("bean的销毁");
    }
}


public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
        UserService userService = applicationContext.getBean("userService", UserService.class);
        System.out.println(userService);
        try {
            userService.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

image.png

四、底层源码剖析

1.bean-ioc具体代码

1⃣️refresh()方法

public void refresh() throws BeansException, IllegalStateException {
        synchronized(this.startupShutdownMonitor) {
            StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
            this.prepareRefresh(); //1.准备,记录容器的启动时间startupDate, 标记容器为激活,初始化上下																		文环境如文件路径信息,验证必填属性是否填写。
            ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();//刷新bean工厂,有则销毁,无则创建:refreshBeanFactory()
            this.prepareBeanFactory(beanFactory);//2.准备bean工厂

            try {
                this.postProcessBeanFactory(beanFactory);//3.空方法
                StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
                this.invokeBeanFactoryPostProcessors(beanFactory);//4.发现bean工厂的处理器
                this.registerBeanPostProcessors(beanFactory);//5.注册bean工厂的处理器到spring容器中,后续可以通过实现接口,重写方法
                beanPostProcess.end();
                this.initMessageSource();//6.国际化消息
                this.initApplicationEventMulticaster();//7.初始化事件多路广播器
                this.onRefresh();//8这.空方法
                this.registerListeners();//9.注册监听器
                this.finishBeanFactoryInitialization(beanFactory);//10.实例化所有bean
                this.finishRefresh();//11.refresh完成
            } catch (BeansException var10) {
                if (this.logger.isWarnEnabled()) {
                    this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var10);
                }
                this.destroyBeans();
                this.cancelRefresh(var10);
                throw var10;
            } finally {
                this.resetCommonCaches();
                contextRefresh.end();
            }
        }
    }

2⃣️finishBeanFactoryInitialization()

    //实例化所有bean
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        if (beanFactory.containsBean("conversionService") && beanFactory.isTypeMatch("conversionService", ConversionService.class)) {
            beanFactory.setConversionService((ConversionService)beanFactory.getBean("conversionService", ConversionService.class));
        }

        if (!beanFactory.hasEmbeddedValueResolver()) {
            beanFactory.addEmbeddedValueResolver((strVal) -> {
                return this.getEnvironment().resolvePlaceholders(strVal);
            });
        }

        String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
        String[] var3 = weaverAwareNames;
        int var4 = weaverAwareNames.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            String weaverAwareName = var3[var5];
            this.getBean(weaverAwareName);
        }

        beanFactory.setTempClassLoader((ClassLoader)null);
        beanFactory.freezeConfiguration();
        beanFactory.preInstantiateSingletons();
    }

3⃣️preInstantiateSingletons()

	public void preInstantiateSingletons() throws BeansException {
		if (logger.isTraceEnabled()) {
			logger.trace("Pre-instantiating singletons in " + this);
		}
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		// 初始化所有非懒加载的bean
		for (String beanName : beanNames) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				if (isFactoryBean(beanName)) {
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					if (bean instanceof FactoryBean) {
						FactoryBean<?> factory = (FactoryBean<?>) bean;
						boolean isEagerInit;
						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
							isEagerInit = AccessController.doPrivileged(
									(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
									getAccessControlContext());
						}
						else {
							isEagerInit = (factory instanceof SmartFactoryBean &&
									((SmartFactoryBean<?>) factory).isEagerInit());
						}
						if (isEagerInit) {
							getBean(beanName);
						}
					}
				}
				else {
					getBean(beanName);
				}
			}
		}

4⃣️getBean():doGetBean()

					try {
						Object scopedInstance = scope.get(beanName, () -> {
							beforePrototypeCreation(beanName);
							try {
								return createBean(beanName, mbd, args);
							}
							finally {
								afterPrototypeCreation(beanName);
							}
						});
						beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}

5⃣️createBean():doCreateBean()

		if (instanceWrapper == null) {
			instanceWrapper = createBeanInstance(beanName, mbd, args);//实例化的实现
		}


    // Initialize the bean instance. 初始化实例化的bean
		Object exposedObject = bean; //bean == null
		try {
			populateBean(beanName, mbd, instanceWrapper);//属性注入
			exposedObject = initializeBean(beanName, exposedObject, mbd); //初始化bean
		}

具体的实例化操作:

createBeanInstance(){
  // No special handling: simply use no-arg constructor. 
		return instantiateBean(beanName, mbd);//没有特殊要求,则使用无参构造
}

instantiateBean(){
  //通过实例化策略实例化
  beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
}

instantiate(){
  constructorToUse = clazz.getDeclaredConstructor();//获取构造器
  return BeanUtils.instantiateClass(constructorToUse);
}

instantiateClass(Constructor<T> ctor, Object... args){
  ctor.newInstance(argsWithDefaultValues);//通过反射实例化
}
populateBean() //属性注入
  	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
  //参数的非空校验
		if (bw == null) {
			if (mbd.hasPropertyValues()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				return;
			}
		}
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
				if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
					return;
				}
			}
		}
//通过byname和bytype的形式
		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

		int resolvedAutowireMode = mbd.getResolvedAutowireMode();
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
			if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}
			if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}
			pvs = newPvs;
      }

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

		PropertyDescriptor[] filteredPds = null;
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
				PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
				if (pvsToUse == null) {
					if (filteredPds == null) {
						filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
					}
					pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						return;
					}
				}
				pvs = pvsToUse;
			}
		}
		if (needsDepCheck) {
			if (filteredPds == null) {
				filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			}
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}

		if (pvs != null) {
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

	protected void autowireByName(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			if (containsBean(propertyName)) {
				Object bean = getBean(propertyName);
				pvs.add(propertyName, bean);
				registerDependentBean(propertyName, beanName);
				if (logger.isTraceEnabled()) {
					logger.trace("Added autowiring by name from bean name '" + beanName +
							"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
							"' by name: no matching bean found");
				}
			}
		}
	}

	protected void autowireByType(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}

		Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			try {
				PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
				// Don't try autowiring by type for type Object: never makes sense,
				// even if it technically is a unsatisfied, non-simple property.
				if (Object.class != pd.getPropertyType()) {
					MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
					// Do not allow eager init for type matching in case of a prioritized post-processor.
					boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
					DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
					Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
					if (autowiredArgument != null) {
						pvs.add(propertyName, autowiredArgument);
					}
					for (String autowiredBeanName : autowiredBeanNames) {
						registerDependentBean(autowiredBeanName, beanName);
						if (logger.isTraceEnabled()) {
							logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
									propertyName + "' to bean named '" + autowiredBeanName + "'");
						}
					}
					autowiredBeanNames.clear();
				}
			}
			catch (BeansException ex) {
				throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
			}
		}
	}
initializeBean() //初始化bean
  applyBeanPostProcessorsBeforeInitialization()//加载初始化前方法
  applyBeanPostProcessorsAfterInitialization()//加载初始化后方法

2.AOP具体代码

1⃣️AbstractAutoProxyCreator类

AbstractAutoProxyCreator{
  public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName){}
  public Object postProcessAfterInitialization(@Nullable Object bean, String beanName){
     if (bean != null) {
            Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
            if (this.earlyProxyReferences.remove(cacheKey) != bean) {
                return this.wrapIfNecessary(bean, beanName, cacheKey);
            }
        }
        return bean;
  }
}
   protected Object getCacheKey(Class<?> beanClass, @Nullable String beanName) {
        if (StringUtils.hasLength(beanName)) {
            return FactoryBean.class.isAssignableFrom(beanClass) ? "&" + beanName : beanName;
        } else {
            return beanClass;
        }
    }
    protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
       Object proxy = this.createProxy(bean.getClass(), //创建代理
                                       beanName, 
                                       specificInterceptors, 
                                       new SingletonTargetSource(bean));
}

createProxy(){
  return proxyFactory.getProxy(classLoader);//传入代理类的类加载器,通过代理工厂得到代理
}

 public Object getProxy(@Nullable ClassLoader classLoader) {
        return this.createAopProxy().getProxy(classLoader);
}

2⃣️DefaultAopProxyFactor类

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {

	@Override
	public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
		if (!NativeDetector.inNativeImage() && (config.isOptimize()
        ||config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) {
			Class<?> targetClass = config.getTargetClass();
			if (targetClass == null) {
				throw new AopConfigException("TargetSource cannot determine target class: " +
						"Either an interface or a target is required for proxy creation.");
			}
			if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
				return new JdkDynamicAopProxy(config); //jdk的动态代理
			}
			return new ObjenesisCglibAopProxy(config);//cjlib的动态代理
		}
		else {
			return new JdkDynamicAopProxy(config);
		}
	}


	private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
		Class<?>[] ifcs = config.getProxiedInterfaces();
		return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
	}
}

3⃣️JdkDynamicAopProxy()方法

	public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
		Assert.notNull(config, "AdvisedSupport must not be null");
		if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
			throw new AopConfigException("No advisors and no TargetSource specified");
		}
		this.advised = config;
		this.proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
		findDefinedEqualsAndHashCodeMethods(this.proxiedInterfaces);
	}

4⃣️CglibAopProxy()方法

	public CglibAopProxy(AdvisedSupport config) throws AopConfigException {
		Assert.notNull(config, "AdvisedSupport must not be null");
		if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
			throw new AopConfigException("No advisors and no TargetSource specified");
		}
		this.advised = config;
		this.advisedDispatcher = new AdvisedDispatcher(this.advised);
	}

5⃣️cglib和jdk动态代理区别

jdk实现cglib实现
实现条件实现被代理类接口继承被代理类
生成效率直接写入class文件基于asm,实现复杂,生成效率低
调用效率通过反射调用,过程多基于fastclass调用,调用速率快
在spring中的配置根据是否有接口可强制使用cglib代理
实现方式InvocationHandler接口实现MethodInterceptor接口

五、相关知识

1.懒加载

概述:

什么是懒加载?默认情况,如果我们spring的bean的作用域是**单例模式(singleton)**的话,那么在spring容器初始化的时候,spring也提前对bean进行了实例化,创建了bean的实例。但是,如果我们想让bean对象在其需要的时候再去实例化的话,那么这种bean对象在其需要的时候实例化的现象就是懒加载

实现:

 <bean id="user" class="test.entity.User" lazy-init="true">
        <property name="name" value="司马昭"></property>
 </bean>

场景:

如果某个bean在应用中很少被使用,那么就可以考虑使用懒加载的方式

2.设计模式

工厂模式:

工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。 在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

image.png 观察者模式:

观察者模式(又被称为发布-订阅(Publish/Subscribe)模式,属于行为型模式的一种,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己。

image.png

单例模式:

  java中单例模式是一种常见的设计模式,单例模式的写法有好几种,这里主要介绍三种:懒汉式单例、饿汉式单例、登记式单例。   单例模式有以下特点:   1、单例类只能有一个实例。   2、单例类必须自己创建自己的唯一实例。   3、单例类必须给所有其他对象提供这一实例。   单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例。这些应用都或多或少具有资源管理器的功能。每台计算机可以有若干个打印机,但只能有一个Printer Spooler,以避免两个打印作业同时输出到打印机中。每台计算机可以有若干通信端口,系统应当集中管理这些通信端口,以避免一个通信端口同时被两个请求同时调用。总之,选择单例模式就是为了避免不一致状态,避免政出多头。