spring-源码阅读记录

    科技2022-07-11  87

    工厂模式

    1、new对象

    public class UserDao { public void test(){ System.out.println("test()方法调用"); } }
    public class UserService { public static void main(String[] args) { UserDao userDao = new UserDao(); userDao.test(); } }

    两个对象之间耦合大,UserDao改动,调用的地方都需要改动。使用工厂模式创建对象,减小UserDao和 UserService 的耦合。

    2、工厂创建对象

    Map作为容器存放各种Bean,key为工厂中的唯一标识,value为创建的对象static静态代码块中反射实例化对象存入map中 public class Factory { //存放对象的容器 private static Map<String, Object> map = new HashMap<String, Object>(); static { try { Constructor<UserDao> constructor = UserDao.class.getDeclaredConstructor(null); UserDao userDao = constructor.newInstance(); map.put("userDao",userDao); } catch (Exception e) { e.printStackTrace(); } } //工具id获取指定的Bean对象 public Object getBean(String beanName){ return map.get(beanName); } } 创建需要的工厂给定id拿到对应的Bean public class UserService { public static void main(String[] args) { Factory factory = new Factory();//获取工厂 UserDao userDao = (UserDao) factory.getBean("userDao");//获得Bean userDao.test(); } }

    3、配置文件

    工厂中创建大量的Bean,将Bean的Id和Bean对象都编写到代码中,不便修改

    将对象ID和对象的包名和类名存入配置文件中方便对工厂中随意添加Bean信息

    userDao=com.wdd.UserDao
    public class Factory { private static Map<String, Object> map = new HashMap<String, Object>(); private static String fileName="bean";//类路径下的配置文件 static { try { ResourceBundle rb = ResourceBundle.getBundle(fileName); Enumeration<String> keys = rb.getKeys();//获取所有的key while (keys.hasMoreElements()){ //遍历所有的key String key = keys.nextElement(); String clazz = rb.getString(key); Class<?> aClass = Class.forName(clazz); Constructor<?> constructor = aClass.getDeclaredConstructor(null); Object instance = constructor.newInstance(); map.put(key,instance); } } catch (Exception e) { e.printStackTrace(); } } public Object getBean(String beanName){ return map.get(beanName); } }

    IOC

    控制反转:

    是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫依赖查找(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。

    对于UserService来说,获取UserDao对象可以通过两种方式获取。一种直接new对象主动获取,一种通过获得工厂传入对象id等待工厂提供对象。把创建对象的主动权交给工厂来控制叫控制反转

    1、spring中的bean.xml

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userDao" class="spring.UserDao"/> <bean id="userService" class="spring.UserService"> <property name="userDao" ref="userDao"/> </bean> </beans>
    public class UserDao { public void testDao(){ System.out.println("Dao的test()方法执行了。。。。"); } }
    public class UserService { private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void testSrvvice(){ userDao.testDao(); System.out.println("service的test()方法执行。。。。"); } }
    public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//获取容器 UserService userService = ac.getBean("userService", UserService.class);//获取对象 userService.testSrvvice(); }

    2、Spring的IOC

    ClassPathXmlApplicationContext类 public ClassPathXmlApplicationContext(String configLocation) throws BeansException { this(new String[]{configLocation},//配置文件名称 true,//refresh (ApplicationContext)null); } ----------------- public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException { super(parent); this.setConfigLocations(configLocations);//设置配置文件路径 if (refresh) { this.refresh();//初始化 } } AbstractApplicationContext类 public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { //1. 准备刷新上下文 prepareRefresh(); // 2.准备刷新内部Bean工厂 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 3.准备使用BeanFactory prepareBeanFactory(beanFactory); try { // 4.空方法,留给子类扩展 postProcessBeanFactory(beanFactory); // 5. 调用BeanFactoryPostProcessors. invokeBeanFactoryPostProcessors(beanFactory); // 6. 注册BeanPostProcessors registerBeanPostProcessors(beanFactory); // 7. 国际化 initMessageSource(); // 8. 初始化上下文多播器 initApplicationEventMulticaster(); // 9.子类实现可实例化自定制的Bean onRefresh(); // 10.检查注册所有的监听器Bean registerListeners(); // 11.实例化所有剩余非延迟的单例 finishBeanFactoryInitialization(beanFactory); // 12.发布相应的事件 finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // 出现异常销毁已创建的Bean destroyBeans(); // 重置‘active’标志 cancelRefresh(ex); // 抛出异常 throw ex; } finally { //重置内存,清除Bean的元信息 resetCommonCaches(); } } } prepareRefresh(); protected void prepareRefresh() { this.startupDate = System.currentTimeMillis();//记录时间 this.closed.set(false); this.active.set(true);//激活 ...... initPropertySources();//初始化占位资源,方法为空留给子类拓展 getEnvironment().validateRequiredProperties();//加载系统配置 ...... //存储预刷新应用程序侦听器 if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); } else { this.applicationListeners.clear(); this.applicationListeners.addAll(this.earlyApplicationListeners); } //发布消息 this.earlyApplicationEvents = new LinkedHashSet<>(); } obtainFreshBeanFactory() protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { refreshBeanFactory(); return getBeanFactory(); } ============== protected final void refreshBeanFactory() throws BeansException { if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory();//创建工厂 beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); this.beanFactory = beanFactory; } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } } prepareBeanFactory() protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // 使用上下文的类加载器 beanFactory.setBeanClassLoader(getClassLoader()); 。。。。。。 // 配置可回调Bean工厂 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); 。。。。。。 //MessageSource注册为Bean beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); // 注册监听器 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); } postProcessBeanFactory(beanFactory) //空方法,留给子类继承对Bean工厂的加强扩展 protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { } invokeBeanFactoryPostProcessors(beanFactory) //Spring此处无处理,SpringBoot在此处完成自动装配 protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } } ========================= 【PostProcessorRegistrationDelegate类】 public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // 首先BeanDefinitionRegistryPostProcessors Set<String> processedBeans = new HashSet<>(); if (beanFactory instanceof BeanDefinitionRegistry) { 。。。。。。 } List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>(); // PriorityOrdered实例化顺序先处理 String[] postProcessorNames =beanFactory.getBeanNamesForType( BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { 。。。。。。 } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); //Ordered实例化顺序处理 postProcessorNames = beanFactory.getBeanNamesForType( BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { 。。。。。。 } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); // 其他为排序的Bean处理 boolean reiterate = true; while (reiterate) { reiterate = false; 。。。。。。 } // BeanFactoryPostProcessors的回调 invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); } registerBeanPostProcessors(beanFactory); protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); } ======== 【PostProcessorRegistrationDelegate类】 public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { String[] postProcessorNames = beanFactory.getBeanNamesForType( BeanPostProcessor.class, true, false); // BeanPostProcessorChecker注册,监听Bean的实例化 int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor( new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // 实现PriorityOrdered的BeanPostProcessor List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); //实现Ordered的BeanPostProcessor List<String> orderedPostProcessorNames = new ArrayList<>(); //常规BeanPostProcessor List<String> nonOrderedPostProcessorNames = new ArrayList<>(); beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); } ====== public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) { if (!isConfigurationFrozen() || type == null || !allowEagerInit) { return doGetBeanNamesForType( ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit); } 。。。。。。 } ====== private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { List<String> result = new ArrayList<>(); // 检查所有的Bean信息 for (String beanName : this.beanDefinitionNames) { 。。。。。。 } // 检查其他注入的Bean for (String beanName : this.manualSingletonNames) { 。。。。。。 } return StringUtils.toStringArray(result); }

    initMessageSource():国际化

    initApplicationEventMulticaster():初始化事件广播器

    onRefresh()

    protected void onRefresh() throws BeansException { //为子类预留,Spring Boot中Tomcat在此处实现 }

    registerListeners();:注册所有的监听器

    finishBeanFactoryInitialization(beanFactory)

    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { 。。。。。。 beanFactory.preInstantiateSingletons(); }
    public void preInstantiateSingletons() throws BeansException { 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)) { 。。。。。。 } else { getBean(beanName); } } } // 所有非延迟单例Bean的回调 for (String beanName : beanNames) {...} } =============== public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); }
    protected <T> T doGetBean( String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)throws BeansException { // 创建Bean,单例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { 。。。。。 return createBean(beanName, mbd, args); 。。。。。。 }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } return (T) bean; }
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException { ...... try { Object beanInstance = doCreateBean(beanName, mbdToUse, args);//创建实例 return beanInstance; } catch (...) {...} }
    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException { // 实例化Bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { instanceWrapper = createBeanInstance(beanName, mbd, args);//实例化 } 。。。 //保存在三级缓存,方便获取引用 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { ... addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // 初始化Bean Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper); exposedObject = initializeBean(beanName, exposedObject, mbd);//初始化Bean } catch (Throwable ex) {。。。} 。。。。。。 return exposedObject; }
    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { // 确保Bean的信息加载 Class<?> beanClass = resolveBeanClass(mbd, beanName); if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {。。。。。。} 。。。。。。 // 创建相同的Bean时创建快捷方式 boolean resolved = false; boolean autowireNecessary = false; if (args == null) {。。。。。。} if (resolved) {。。。。。。} // 自动装配时的候选构造函数 Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { return autowireConstructor(beanName, mbd, ctors, args); } // 有优先的构造器 ctors = mbd.getPreferredConstructors(); if (ctors != null) { return autowireConstructor(beanName, mbd, ctors, null); } // 无特殊处理,直接无参构造 return instantiateBean(beanName, mbd); } 实例化Bean protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) { try { Object beanInstance; if (System.getSecurityManager() != null) {。。。 } else { beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this); } } catch (Throwable ex) {。。。 } }
    public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) { ... return BeanUtils.instantiateClass(constructorToUse); ... }
    public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException { Assert.notNull(ctor, "Constructor must not be null"); try { ReflectionUtils.makeAccessible(ctor); if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector. isKotlinType(ctor.getDeclaringClass())) { return KotlinDelegate.instantiateClass(ctor, args); } else { Class<?>[] parameterTypes = ctor.getParameterTypes(); ... return ctor.newInstance(argsWithDefaultValues);//返回反射创建的对象 } } catch (ex) {...} }
    初始化Bean protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) { 。。。 //PostProcessorsBeforeInitialization方法执行 Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } //自定义InitMethod执行 try { invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) {。。。} //BeanPostProcessorsAfterInitialization方法执行 if (mbd == null || !mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessBeforeInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }

    3、Spring的AOP

    public interface BeanPostProcessor { default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }

    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 wrapIfNecessary(Object bean, String beanName, Object cacheKey) { if (...) {... } else if (...) {... } else if (...) {... if (...) { Object proxy = this.createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); this.proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } else {...} } else {...} }
    protected Object createProxy(Class<?> beanClass, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) { 。。。。。。 return proxyFactory.getProxy(this.getProxyClassLoader()); }
    public Object getProxy(@Nullable ClassLoader classLoader) { return this.createAopProxy().getProxy(classLoader); }

    JDK public Object getProxy(@Nullable ClassLoader classLoader) { if (logger.isTraceEnabled()) { logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource()); } Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true); this.findDefinedEqualsAndHashCodeMethods(proxiedInterfaces); return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this); } Cglib public Object getProxy(@Nullable ClassLoader classLoader) { ...... return this.createProxyClassAndInstance(enhancer, callbacks); }
    protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) { enhancer.setInterceptDuringConstruction(false); enhancer.setCallbacks(callbacks); return this.constructorArgs != null && this.constructorArgTypes != null ? enhancer.create(this.constructorArgTypes, this.constructorArgs) : enhancer.create(); }
    Processed: 0.058, SQL: 8