SpringIOC refresh()初始化代码实例

finishBeanFactoryInitialization(beanFactory):初始化不需要延迟实例化的单例bean

/* org/springframework/context/support/AbstractApplicationContext.java:870 */
  protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {//初始化容器的conversionService
    if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
        beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
      beanFactory.setConversionService(
          beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
    }
//如果没有任何一个类似PropertyPlaceholderConfigurer bean处理器
    //默认一个嵌入式值解析器,主要是为了解析属性值例如数据库连接中${password}等属性解析
    if (!beanFactory.hasEmbeddedValueResolver()) {
      beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }
// 先实例化LoadTimeWeaverAware相关的beans,以便尽早转换,AOP相关
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
      getBean(weaverAwareName);
    }

//删除临时类加载器,停止临时类加载器进行类型匹配
    beanFactory.setTempClassLoader(null);

//拷贝beandefinitionNames到frozenBeanDefinitionNames
    beanFactory.freezeConfiguration();

    // 实例化所有不需要延迟初始化的单例bean
    beanFactory.preInstantiateSingletons();
  }

beanFactory.preInstantiateSingletons():实例化所有不需要延迟初始化的单例bean

/* org/springframework/beans/factory/support/DefaultListableBeanFactory.java:885 */
  public void preInstantiateSingletons() throws BeansException {
    if (logger.isTraceEnabled()) {
      logger.trace("Pre-instantiating singletons in " + this);
    }

    // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    //拷贝beanDefinitionNames副本,考虑到遍历中其他线程可能修改beandefinitionNames
    // ArrayList类型遍历时规避fast-fail,实现fast-safe
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    for (String beanName : beanNames) {
      //当bean存在parentBean时的继承关系
      //① bean不存在parentBean时,创建一个new RootBeanDefinition(beandefinition)返回。
      //② bean存在parentBean时,支持继承关系
      // 需要先创建parentBean的new RootBeanDefinition(parentBeanDefinition)
      // 然后用beandefinition覆盖parentBean的RootBeanDefinition的相关属性并返回。superBean.overrideFrom(subBean);
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      //用mergedLocalBeanDefinition判断是否需要初始化
      //筛选不是抽象类且不是延迟实例化的单例进行初始化
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
        if (isFactoryBean(beanName)) {
          //工厂Bean beanName=&beanName
          Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
          if (bean instanceof FactoryBean) {
            final 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 {
          //不是工厂bean 直接初始化
          getBean(beanName);
        }
      }
    }

    //SmartInitializingSingleton类型的单例初始化后的回调
    for (String beanName : beanNames) {
      Object singletonInstance = getSingleton(beanName);
      if (singletonInstance instanceof SmartInitializingSingleton) {
        final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
        if (System.getSecurityManager() != null) {
          AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            smartSingleton.afterSingletonsInstantiated();
            return null;
          }, getAccessControlContext());
        }
        else {
          smartSingleton.afterSingletonsInstantiated();
        }
      }
    }
  }

getBean(beanName):Bean初始化

/* org/springframework/beans/factory/support/AbstractBeanFactory.java:414 */
  protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
      @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
    //如果是aliaName,解析成beanName
    final String beanName = transformedBeanName(name);
    Object bean;

    // Eagerly check singleton cache for manually registered singletons.
    //检查单例缓存中是否存在bean的实例化对象、初始化对象 (涉及循环依赖解决,需要先分清出Bean的两个阶段实例化、初始化)
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
      if (logger.isTraceEnabled()) {
        if (isSingletonCurrentlyInCreation(beanName)) {
          logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
              "' that is not fully initialized yet - a consequence of a circular reference");
        }
        else {
          logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
        }
      }
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
      if (isPrototypeCurrentlyInCreation(beanName)) {
        //多例bean正在初始化时抛出异常
        //由于多例bean,每调用一次getBean就会创建一个实例,
        //所以通过ThreadLocal打标,来避免单个线程的重复创建
        throw new BeanCurrentlyInCreationException(beanName);
      }

      BeanFactory parentBeanFactory = getParentBeanFactory();
      //父容器不为空,用父容器初始化
      if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
        // Not found -> check parent.
        String nameToLookup = originalBeanName(name);
        if (parentBeanFactory instanceof AbstractBeanFactory) {
          return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
              nameToLookup, requiredType, args, typeCheckOnly);
        }
        else if (args != null) {
          // Delegation to parent with explicit args.
          return (T) parentBeanFactory.getBean(nameToLookup, args);
        }
        else if (requiredType != null) {
          // No args -> delegate to standard getBean method.
          return parentBeanFactory.getBean(nameToLookup, requiredType);
        }
        else {
          return (T) parentBeanFactory.getBean(nameToLookup);
        }
      }

      if (!typeCheckOnly) {
        //alreadyCreated容器记录已经被实例化的beanName,
        //这里将beanName添加到alreadyCreated
        markBeanAsCreated(beanName);
      }

      try {
        //重新获取mergedLocalBeanDefinition(bean与parentBean合并)
        final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
        //检查mbd不是抽象类
        checkMergedBeanDefinition(mbd, beanName, args);

        //创建bean单例之前,需要保证先bean所依赖的Bean单例已创建,
        //这里的依赖对应@dependsOn声明的依赖,这个注解不常用,这里也会出现一种循环依赖场景,与我们平常讨论的引用循环依赖不同
        //@dependsOn(value = "b") class A;@dependsOn(value = "a") class B
        //如果出现这种循环依赖 会直接抛出异常 启动失败
        String[] dependsOn = mbd.getDependsOn();
        if (dependsOn != null) {
          for (String dep : dependsOn) {
            if (isDependent(beanName, dep)) {
              throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                  "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
            }
            //保存依赖关系到dependentBeanMap容器中
            registerDependentBean(dep, beanName);
            try {
              //实例化依赖的bean 这里就是常见循环依赖地点 A依赖B B依赖A
              getBean(dep);
            }
            catch (NoSuchBeanDefinitionException ex) {
              throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                  "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
            }
          }
        }

        // Create bean instance.
        if (mbd.isSingleton()) {
          //单例Bean创建 先取缓存,没有才createBean
          sharedInstance = getSingleton(beanName, () -> {
            try {
              //创建Bean实例
              return createBean(beanName, mbd, args);
            }
            catch (BeansException ex) {
              destroySingleton(beanName);
              throw ex;
            }
          });
          bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
        }

        else if (mbd.isPrototype()) {
          //多例Bean创建 直接createbean
          Object prototypeInstance = null;
          try {
            //正在创建bean打标prototypesCurrentlyInCreation
            //与上面isPrototypeCurrentlyInCreation()联合
            beforePrototypeCreation(beanName);
            prototypeInstance = createBean(beanName, mbd, args);
          }
          finally {
            //正在创建bean打标prototypesCurrentlyInCreation删除标记
            afterPrototypeCreation(beanName);
          }
          bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
        }

        else {
            //自定义scope初始化、scope.get()
          String scopeName = mbd.getScope();
          final Scope scope = this.scopes.get(scopeName);
          if (scope == null) {
            throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
          }
          try {
            Object scopedInstance = scope.get(beanName, () -> {
              beforePrototypeCreation(beanName);
              try {
                return createBean(beanName, mbd, args);
              }
              finally {
                afterPrototypeCreation(beanName);
              }
            });
            bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
          }
          catch (IllegalStateException ex) {
            throw new BeanCreationException(beanName,
                "Scope '" + scopeName + "' is not active for the current thread; consider " +
                "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                ex);
          }
        }
      }
      catch (BeansException ex) {
        cleanupAfterBeanCreationFailure(beanName);
        throw ex;
      }
    }
//getBean(beanName,requiredType)时检查创建的实例是否需要的类型,容器初始化时不会走进里面
    if (requiredType != null && !requiredType.isInstance(bean)) {
      try {
        T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
        if (convertedBean == null) {
          throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
        return convertedBean;
      }
      catch (TypeMismatchException ex) {
        if (logger.isTraceEnabled()) {
          logger.trace("Failed to convert bean '" + name + "' to required type '" +
              ClassUtils.getQualifiedName(requiredType) + "'", ex);
        }
        throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
      }
    }
    return (T) bean;
  }

sharedInstance = getSingleton(beanName, () -> {try {return createBean(beanName, mbd, args);}:单例初始化,这个方法比较简单,主要关注下和循坏依赖相关的逻辑

/* org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java:201 */
  public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
    Assert.notNull(beanName, "Bean name must not be null");
    synchronized (this.singletonObjects) {
      Object singletonObject = this.singletonObjects.get(beanName);
      if (singletonObject == null) {
        if (this.singletonsCurrentlyInDestruction) {
          throw new BeanCreationNotAllowedException(beanName,
              "Singleton bean creation not allowed while singletons of this factory are in destruction " +
              "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
        }
        if (logger.isDebugEnabled()) {
          logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
        }
        //循环依赖相关:初始化前先singletonsCurrentlyInCreation.add(beanName)
        beforeSingletonCreation(beanName);
        boolean newSingleton = false;
        boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
        if (recordSuppressedExceptions) {
          this.suppressedExceptions = new LinkedHashSet<>();
        }
        try {
          //lamda表达式:其实是调用createBean(beanName, mbd, args):Bean初始化
          singletonObject = singletonFactory.getObject();
          newSingleton = true;
        }
        catch (IllegalStateException ex) {
          // Has the singleton object implicitly appeared in the meantime ->
          // if yes, proceed with it since the exception indicates that state.
          singletonObject = this.singletonObjects.get(beanName);
          if (singletonObject == null) {
            throw ex;
          }
        }
        catch (BeanCreationException ex) {
          if (recordSuppressedExceptions) {
            for (Exception suppressedException : this.suppressedExceptions) {
              ex.addRelatedCause(suppressedException);
            }
          }
          throw ex;
        }
        finally {
          if (recordSuppressedExceptions) {
            this.suppressedExceptions = null;
          }
          //循环依赖相关:初始化后singletonsCurrentlyInCreation.remove(beanName)
          afterSingletonCreation(beanName);
        }
        if (newSingleton) {
          //初始化完后
          //this.singletonObjects.put(beanName, singletonObject);放入到单例容器中
          //this.singletonFactories.remove(beanName);清空循环依赖相关的两个打标
          //this.earlySingletonObjects.remove(beanName);
          //this.registeredSingletons.add(beanName);放入单例beanName容器中
          addSingleton(beanName, singletonObject);
        }
      }
      return singletonObject;
    }
  }

createBean(beanName, mbd, args):初始化实例,这个表方法注意一下,初始化实例前,留机会给BeanPostProcessor初始化代理类直接返回代理类初始化实例

/* org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:467 */
  protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
      throws BeanCreationException {

    if (logger.isTraceEnabled()) {
      logger.trace("Creating instance of bean '" + beanName + "'");
    }
    RootBeanDefinition mbdToUse = mbd;

    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
      //确保beanclass确实被解析了,若合并出错,重新定义bean定义
      mbdToUse = new RootBeanDefinition(mbd);
      mbdToUse.setBeanClass(resolvedClass);
    }

    // Prepare method overrides.
    try {
      //校验需要重写方法是否全部重写,并且会给重写方法是否重载打标
      mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
      throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
          beanName, "Validation of method overrides failed", ex);
    }

    try {
      //resolveBeforeInstantiation方法是调用BeanPostProcessor处理器
      //后续研究一下BeanPostProcessor
      //这里是给AOP相关BeanPostProcessor处理器生成代理类实例的机会,直接生成初始化代理类实例返回
      //会面研究AOP时发现,proxy object不是在这里初始化,这里只是提供一个机会
      //proxy object具体是在的下面doCreateBean时里先创建target object
      //然后通过后置处理器的后置方法初始化的
      Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
      if (bean != null) {
        return bean;
      }
    }
    catch (Throwable ex) {
      throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
          "BeanPostProcessor before instantiation of bean failed", ex);
    }

    try {
      //初始化实例
      Object beanInstance = doCreateBean(beanName, mbdToUse, args);
      if (logger.isTraceEnabled()) {
        logger.trace("Finished creating instance of bean '" + beanName + "'");
      }
      return beanInstance;
    }
    catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
      // A previously detected exception with proper bean creation context already,
      // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
      throw ex;
    }
    catch (Throwable ex) {
      throw new BeanCreationException(
          mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
    }
  }

doCreateBean(beanName,mbdToUse,args):beanClass实例化(即earlysingleton,注意不是初始化)然后DI完成初始化

/* org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:549 */
  protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
      throws BeanCreationException {

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
      //反射调用beanClass的构造方法创建实例并包装成beanwrapper--
      instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
      mbd.resolvedTargetType = beanType;
    }

    // Allow post-processors to modify the merged bean definition.
    //允许MergedBeanDefinitionPostProcessors后置管理器修改rootBeandefinition
    synchronized (mbd.postProcessingLock) {
      if (!mbd.postProcessed) {
        try {
          applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
        }
        catch (Throwable ex) {
          throw new BeanCreationException(mbd.getResourceDescription(), beanName,
              "Post-processing of merged bean definition failed", ex);
        }
        mbd.postProcessed = true;
      }
    }

    // Eagerly cache singletons to be able to resolve circular references
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
        isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
      if (logger.isTraceEnabled()) {
        logger.trace("Eagerly caching bean '" + beanName +
            "' to allow for resolving potential circular references");
      }
      //循环依赖相关逻辑:
      //this.singletonFactories.put(beanName, singletonFactory);
      //将实例化bean、beanName组装成singletonFactory装入singletonFactories容器
      //this.earlySingletonObjects.remove(beanName);
      //删除earlySingletonObjects中beanName
      addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    //创建实例
    Object exposedObject = bean;
    try {
      //实例初始化 就是在这里面实现依赖注入DI的:
      //具体是调用AutowiredAnnotationBeanPostProcessor.postProcessProperties
      populateBean(beanName, mbd, instanceWrapper);//调用Bean后置管理器前置方法BeanPostProcessor.postProcessBeforeInitialization
      //instanceof aware接口,setBeanName setBeanClassLoader setBeanFactory
      //调用Bean后置管理器后置方法BeanPostProcessor.postProcessAfterInitialization
      exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    catch (Throwable ex) {
      if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
        throw (BeanCreationException) ex;
      }
      else {
        throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
      }
    }
    //...
    return exposedObject;
  }

populateBean(beanName, mbd, instanceWrapper):依赖注入DI执行时机

/* org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:1381 */
  protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    //...
    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
      if (pvs == null) {
        pvs = mbd.getPropertyValues();
      }
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
        if (bp instanceof InstantiationAwareBeanPostProcessor) {
          InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
          //这里调用AutowiredAnnotationBeanPostProcessor.postProcessProperties()
          //完成注解自动注入(DI)
          PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
          if (pvsToUse == null) {
            if (filteredPds == null) {
              filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            }
            pvsToUse = ibp.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);
    }
  }

DI结束,bean初始化基本结束了。然后就是bean初始化的BeanPostProcessor执行前置后置方法

BeanPostProcessor前置后置方法:一些很重要架构都需要依靠实现,例如AOP动态代理产生代理对象

AnnotationAwareAspectJAutoProxyCreator.postProcessAfterInitialization

/* org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition) */
  protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
      AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
        invokeAwareMethods(beanName, bean);
        return null;
      }, getAccessControlContext());
    }
    else {
      invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
      //调用所有BeanPostProcessor前置方法BeanPostProcessor.postProcessBeforeInitialization
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
      invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
      throw new BeanCreationException(
          (mbd != null ? mbd.getResourceDescription() : null),
          beanName, "Invocation of init method failed", ex);
    }
    if (mbd == null || !mbd.isSynthetic()) {
      //调用所有BeanPostProcessor前置方法BeanPostProcessor.postProcessAfterInitialization
      //例如AOP代理对象就是这里初始化的,AnnotationAwareAspectJAutoProxyCreator.postProcessAfterInitialization
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
  }

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

(0)

相关推荐

  • Spring的refresh()方法相关异常解析

    Spring是一个开放源代码的设计层面框架,他解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应用.Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建.简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架. 如果是经常使用Spring,特别有自己新建ApplicationContext对象的经历的人,肯定见过这么几条异常消息: 1.LifecycleProcessornoti

  • Spring Bean的初始化和销毁实例详解

    本文实例讲述了Spring Bean的初始化和销毁.分享给大家供大家参考,具体如下: 一 点睛 在开发过程中,经常遇到在Bean使用之前或者之后做一些必要的操作,Spring对Bean的生命周期的操作提供了支持. 1 Java配置方式:使用@Bean的initMethod和destroyMethod. 2 注解方式:利用JSR-250的@PostConstruct和@PreDestroy. 二 实战 1 增加JSR250支持 <dependency> <groupId>javax.

  • Spring初始化和销毁的实现方法

    这篇文章主要介绍了Spring初始化和销毁的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一 指定初始化和销毁方法 通过@Bean指定init-method和destroy-method: @Bean(initMethod="init",destroyMethod="detory") public Car car(){ return new Car(); } 二 通过让Bean实现Initializing

  • 在Spring Boot中加载初始化数据的实现

    在Spring Boot中,Spring Boot会自动搜索映射的Entity,并且创建相应的table,但是有时候我们希望自定义某些内容,这时候我们就需要使用到data.sql和schema.sql. 依赖条件 Spring Boot的依赖我们就不将了,因为本例将会有数据库的操作,我们这里使用H2内存数据库方便测试: <dependency> <groupId>com.h2database</groupId> <artifactId>h2</arti

  • springboot实现rabbitmq的队列初始化和绑定

    配置文件,在rabbit中自动建立exchange,queue和绑定它们的关系 代码里初始化exchange 代码里初始化queue 代码里绑定exchange,queue和routekey 配置文件,直接声明vhost 代码里初始化exchange /** * rabbitMq里初始化exchange. * * @return */ @Bean public TopicExchange crmExchange() { return new TopicExchange(EXCHANGE); }

  • Spring Bean初始化及销毁多种实现方式

    这篇文章主要介绍了Spring Bean初始化及销毁多种实现方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.前言 日常开发过程有时需要在应用启动之后加载某些资源,或者在应用关闭之前释放资源.Spring 框架提供相关功能,围绕 Spring Bean 生命周期,可以在 Bean 创建过程初始化资源,以及销毁 Bean 过程释放资源.Spring 提供多种不同的方式初始化/销毁 Bean,如果同时使用这几种方式,Spring 如何处理这几

  • Spring Boot 初始化运行特定方法解析

    Spring Boot提供了两种 "开机自启动" 的方式,ApplicationRunner和CommandLineRunner 这两种方式的目的是为了满足,在容器启动时like执行某些方法.我们可以通过实现ApplicationRunner或者CommandLineRunner来实现,他们都是在SpringAppliaction执行之后开始执行的.这个特性可以让我们自定义一些在容器启动时需要初始化的逻辑 ApplicationRunner接口: 官方doc: Interface us

  • Spring Cloud @RefreshScope 原理及使用

    @RefreshScope那些事 要说清楚RefreshScope,先要了解Scope Scope(org.springframework.beans.factory.config.Scope)是Spring 2.0开始就有的核心的概念 RefreshScope(org.springframework.cloud.context.scope.refresh)是spring cloud提供的一种特殊的scope实现,用来实现配置.实例热加载. Scope -> GenericScope -> R

  • SpringIOC refresh()初始化代码实例

    finishBeanFactoryInitialization(beanFactory):初始化不需要延迟实例化的单例bean /* org/springframework/context/support/AbstractApplicationContext.java:870 */ protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {//初始化容器的convers

  • VC++角色游戏中的人物初始化模块代码实例

    本文以一个实例讲述VC++游戏中的人物角色动画初始化实现代码,本代码只是实现人物角色动画的初始化,不包括其它功能,并不是完整的一个游戏应用,现在将这个角色初始化代码与大家分享.希望能够对大家学习VC++有所帮助. #include "StdAfx.h" #include "Character.h" CCharacter::CCharacter(void) { } CCharacter::~CCharacter(void) { } //初始化人物 bool CChar

  • JavaWeb Refresh响应头代码实例详解

    这篇文章主要介绍了JavaWeb Refresh响应头代码实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.Refresh响应头:可以理解为定时的重定向,在指定的时间后发生页面的跳转 二.代码示例: package cn.xxx.Servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Ht

  • 多种类型jQuery网页验证码插件代码实例

    html <!DOCTYPE html> <html lang="zh-cn"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,m

  • BootstrapTable refresh 方法使用实例简单介绍

    本文就bootstrapTable refresh 方法如何传递参数做简单举例说明.下面代码中,一个table,一个button,单击button会触发刷新表格操作. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="../libs/bootstrap

  • java对象初始化代码详解

    本文主要记录JAVA中对象的初始化过程,包括实例变量的初始化和类变量的初始化以及final关键字对初始化的影响.另外,还讨论了由于继承原因,探讨了引用变量的编译时类型和运行时类型 一,实例变量的初始化 这里首先介绍下创建对象的过程: 类型为Dog的一个对象首次创建时,或者Dog类的static字段或static方法首次访问时,Java解释器必须找到Dog.class(在事先设定好的路径里面搜索):  找到Dog.class后(它会创建一个Class对象),它的所有static初始化模块都会运行.

  • js实现图片推拉门效果代码实例

    初学者. 推拉门是网页中常见的一种形式,通过JS实现比较简单.主要是通过getElement找到节点元素,然后对其进行相应的赋值即可. 新建一个index.html文件,并在同一个目录中添加三个文件夹,images(用来当作"门"的图片),styles(用来存放css文件),scripts(用来存放js文件).然后在index.html中添加代码: <!doctype html> <html> <head> <meta charset=&quo

  • Python进度条的制作代码实例

    这篇文章主要介绍了Python进度条的制作代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 import sys,time #导入模块 for i in range(50): #进度条的长度 sys.stdout.write("#") #进度条的内容,这里要注意了,pycharm有可能不显示write的方法 sys.stdout.flush() #刷新缓存 time.sleep(0.5) #间隔时间,和shell的sleep差不

  • SpringBoot加入Guava Cache实现本地缓存代码实例

    这篇文章主要介绍了SpringBoot加入Guava Cache实现本地缓存代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在pom.xml中加入guava依赖 <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version>

  • js图数据结构处理 迪杰斯特拉算法代码实例

    这篇文章主要介绍了js图数据结构处理 迪杰斯特拉算法代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 /*//1.确定数据结构, mapf[i][j] 为点i到点j的距离 [ Infinity 2 5 Infinity Infinity Infinity Infinity 2 6 Infinity Infinity Infinity Infinity 7 1 Infinity Infinity 2 Infinity 4 Infinity

随机推荐