国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Spring @Configuration和@Component的區(qū)別

Spring @Configuration和@Component的區(qū)別

2019-06-27 17:06isea533 Java教程

今天小編就為大家分享一篇關(guān)于Spring @Configuration和@Component的區(qū)別,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧

Spring @Configuration 和 @Component 區(qū)別

一句話概括就是 @Configuration 中所有帶 @Bean 注解的方法都會被動態(tài)代理,因此調(diào)用該方法返回的都是同一個實例。

下面看看實現(xiàn)的細(xì)節(jié)。

@Configuration 注解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
  String value() default "";
}

從定義來看,@Configuration 注解本質(zhì)上還是@Component,因此<context:component-scan/> 或者 @ComponentScan都能處理@Configuration注解的類。

@Configuration標(biāo)記的類必須符合下面的要求:

  • 配置類必須以類的形式提供(不能是工廠方法返回的實例),允許通過生成子類在運行時增強(cglib 動態(tài)代理)。
  • 配置類不能是 final 類(沒法動態(tài)代理)。
  • 配置注解通常為了通過 @Bean 注解生成 Spring 容器管理的類,
  • 配置類必須是非本地的(即不能在方法中聲明,不能是 private)。
  • 任何嵌套配置類都必須聲明為static。
  • @Bean 方法可能不會反過來創(chuàng)建進一步的配置類(也就是返回的 bean 如果帶有 @Configuration,也不會被特殊處理,只會作為普通的 bean)。

加載過程

Spring 容器在啟動時,會加載默認(rèn)的一些PostPRocessor,其中就有ConfigurationClassPostProcessor,這個后置處理程序?qū)iT處理帶有@Configuration注解的類,這個程序會在bean 定義加載完成后,在bean初始化前進行處理。主要處理的過程就是使用cglib動態(tài)代理增強類,而且是對其中帶有@Bean注解的方法進行處理。

在ConfigurationClassPostProcessor 中的 postProcessBeanFactory 方法中調(diào)用了下面的方法:

/**
 * Post-processes a BeanFactory in search of Configuration class BeanDefinitions;
 * any candidates are then enhanced by a {@link ConfigurationClassEnhancer}.
 * Candidate status is determined by BeanDefinition attribute metadata.
 * @see ConfigurationClassEnhancer
 */
public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
  Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<String, AbstractBeanDefinition>();
  for (String beanName : beanFactory.getBeanDefinitionNames()) {
    BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
    if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
      //省略部分代碼
      configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
    }
  }
  if (configBeanDefs.isEmpty()) {
    // nothing to enhance -> return immediately
    return;
  }
  ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
  for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
    AbstractBeanDefinition beanDef = entry.getValue();
    // If a @Configuration class gets proxied, always proxy the target class
    beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
    try {
      // Set enhanced subclass of the user-specified bean class
      Class<?> configClass = beanDef.resolveBeanClass(this.beanClassLoader);
      Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
      if (configClass != enhancedClass) {
        //省略部分代碼
        beanDef.setBeanClass(enhancedClass);
      }
    }
    catch (Throwable ex) {
      throw new IllegalStateException(
       "Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
    }
  }
}

在方法的第一次循環(huán)中,查找到所有帶有@Configuration注解的 bean 定義,然后在第二個 for 循環(huán)中,通過下面的方法對類進行增強:

Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);

然后使用增強后的類替換了原有的beanClass

beanDef.setBeanClass(enhancedClass);

所以到此時,所有帶有@Configuration注解的 bean 都已經(jīng)變成了增強的類。

下面關(guān)注上面的enhance增強方法,多跟一步就能看到下面的方法:

/**
 * Creates a new CGLIB {@link Enhancer} instance.
 */
private Enhancer newEnhancer(Class<?> superclass, ClassLoader classLoader) {
  Enhancer enhancer = new Enhancer();
  enhancer.setSuperclass(superclass);
  enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class});
  enhancer.setUseFactory(false);
  enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
  enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader));
  enhancer.setCallbackFilter(CALLBACK_FILTER);
  enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());
  return enhancer;
}

通過 cglib 代理的類在調(diào)用方法時,會通過CallbackFilter調(diào)用,這里的CALLBACK_FILTER如下:

// The callbacks to use. Note that these callbacks must be stateless.
private static final Callback[] CALLBACKS = new Callback[] {
    new BeanMethodInterceptor(),
    new BeanFactoryAwareMethodInterceptor(),
    NoOp.INSTANCE
};
private static final ConditionalCallbackFilter CALLBACK_FILTER = 
    new ConditionalCallbackFilter(CALLBACKS);

其中BeanMethodInterceptor匹配方法如下:

@Override
public boolean isMatch(Method candidateMethod) {
  return BeanAnnotationHelper.isBeanAnnotated(candidateMethod);
}
//BeanAnnotationHelper
public static boolean isBeanAnnotated(Method method) {
  return AnnotatedElementUtils.hasAnnotation(method, Bean.class);
}

也就是當(dāng)方法有@Bean注解的時候,就會執(zhí)行這個回調(diào)方法。

另一個BeanFactoryAwareMethodInterceptor匹配的方法如下:

@Override
public boolean isMatch(Method candidateMethod) {
  return (candidateMethod.getName().equals("setBeanFactory") &&
      candidateMethod.getParameterTypes().length == 1 &&
      BeanFactory.class == candidateMethod.getParameterTypes()[0] &&
      BeanFactoryAware.class.isAssignableFrom(candidateMethod.getDeclaringClass()));
}

當(dāng)前類還需要實現(xiàn)BeanFactoryAware接口,上面的isMatch就是匹配的這個接口的方法。

@Bean 注解方法執(zhí)行策略

先給一個簡單的示例代碼:

@Configuration
public class MyBeanConfig {
  @Bean
  public Country country(){
    return new Country();
  }
  @Bean
  public UserInfo userInfo(){
    return new UserInfo(country());
  }
}

相信大多數(shù)人第一次看到上面 userInfo() 中調(diào)用 country() 時,會認(rèn)為這里的 Country 和上面 @Bean 方法返回的 Country 可能不是同一個對象,因此可能會通過下面的方式來替代這種方式:

@Autowired 
private Country country;

實際上不需要這么做(后面會給出需要這樣做的場景),直接調(diào)用 country() 方法返回的是同一個實例。

下面看調(diào)用 country() 和 userInfo() 方法時的邏輯。

現(xiàn)在我們已經(jīng)知道@Configuration注解的類是如何被處理的了,現(xiàn)在關(guān)注上面的BeanMethodInterceptor,看看帶有 @Bean注解的方法執(zhí)行的邏輯。下面分解來看intercept方法。

//首先通過反射從增強的 Configuration 注解類中獲取 beanFactory
ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance);
//然后通過方法獲取 beanName,默認(rèn)為方法名,可以通過 @Bean 注解指定
String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod);
//確定這個 bean 是否指定了代理的范圍
//默認(rèn)下面 if 條件 false 不會執(zhí)行
Scope scope = AnnotatedElementUtils.findMergedAnnotation(beanMethod, Scope.class);
if (scope != null && scope.proxyMode() != ScopedProxyMode.NO) {
  String scopedBeanName = ScopedProxyCreator.getTargetBeanName(beanName);
  if (beanFactory.isCurrentlyInCreation(scopedBeanName)) {
    beanName = scopedBeanName;
  }
}
//中間跳過一段 Factorybean 相關(guān)代碼
//判斷當(dāng)前執(zhí)行的方法是否為正在執(zhí)行的 @Bean 方法
//因為存在在 userInfo() 方法中調(diào)用 country() 方法
//如果 country() 也有 @Bean 注解,那么這個返回值就是 false.
if (isCurrentlyInvokedFactoryMethod(beanMethod)) {
  // 判斷返回值類型,如果是 BeanFactoryPostProcessor 就寫警告日志
  if (logger.isWarnEnabled() &&
      BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
    logger.warn(String.format(
      "@Bean method %s.%s is non-static and returns an object " +
      "assignable to Spring's BeanFactoryPostProcessor interface. This will " +
      "result in a failure to process annotations such as @Autowired, " +
      "@Resource and @PostConstruct within the method's declaring " +
      "@Configuration class. Add the 'static' modifier to this method to avoid " +
      "these container lifecycle issues; see @Bean javadoc for complete details.",
      beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));
  }
  //直接調(diào)用原方法創(chuàng)建 bean
  return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
}
//如果不滿足上面 if,也就是在 userInfo() 中調(diào)用的 country() 方法
return obtainBeanInstanceFromFactory(beanMethod, beanMethodArgs, beanFactory, beanName);

關(guān)于isCurrentlyInvokedFactoryMethod方法

可以參考 SimpleInstantiationStrategy 中的 instantiate 方法,這里先設(shè)置的調(diào)用方法:

currentlyInvokedFactoryMethod.set(factoryMethod);
return factoryMethod.invoke(factoryBean, args);

而通過方法內(nèi)部直接調(diào)用 country() 方法時,不走上面的邏輯,直接進的代理方法,也就是當(dāng)前的 intercept方法,因此當(dāng)前的工廠方法和執(zhí)行的方法就不相同了。

obtainBeanInstanceFromFactory方法比較簡單,就是通過beanFactory.getBean獲取Country,如果已經(jīng)創(chuàng)建了就會直接返回,如果沒有執(zhí)行過,就會通過invokeSuper首次執(zhí)行。

因此我們在@Configuration注解定義的 bean 方法中可以直接調(diào)用方法,不需要@Autowired注入后使用。

@Component 注意

@Component注解并沒有通過 cglib 來代理@Bean方法的調(diào)用,因此像下面這樣配置時,就是兩個不同的 country。

@Component
public class MyBeanConfig {
  @Bean
  public Country country(){
    return new Country();
  }
  @Bean
  public UserInfo userInfo(){
    return new UserInfo(country());
  }
}

有些特殊情況下,我們不希望MyBeanConfig被代理(代理后會變成WebMvcConfig$$EnhancerBySpringCGLIB$$8bef3235293)時,就得用@Component,這種情況下,上面的寫法就需要改成下面這樣:

@Component
public class MyBeanConfig {
  @Autowired
  private Country country;
  @Bean
  public Country country(){
    return new Country();
  }
  @Bean
  public UserInfo userInfo(){
    return new UserInfo(country);
  }
}

這種方式可以保證使用的同一個Country實例。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對服務(wù)器之家的支持。

延伸 · 閱讀

精彩推薦
  • Java教程SpringBoot引入Thymeleaf的實現(xiàn)方法

    SpringBoot引入Thymeleaf的實現(xiàn)方法

    這篇文章主要介紹了SpringBoot引入Thymeleaf的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下...

    Bobby6472021-07-28
  • Java教程JavaWeb 實現(xiàn)驗證碼功能(demo)

    JavaWeb 實現(xiàn)驗證碼功能(demo)

    在 WEB-APP 中一般應(yīng)用于:登錄、注冊、買某票、秒殺等場景,大家都接觸過這個驗證碼操作,今天小編通過實例代碼給大家講解javaweb實現(xiàn)驗證碼功能,需要...

    java教程網(wǎng)12832020-08-05
  • Java教程Java之Springcloud Feign組件詳解

    Java之Springcloud Feign組件詳解

    這篇文章主要介紹了Java之Springcloud Feign組件詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下...

    深情以改10322021-11-12
  • Java教程java 中鎖的性能提高辦法

    java 中鎖的性能提高辦法

    這篇文章主要介紹了java 中鎖的性能提高辦法的相關(guān)資料,需要的朋友可以參考下...

    Java之家3092020-08-13
  • Java教程JAVA中通過自定義注解進行數(shù)據(jù)驗證的方法

    JAVA中通過自定義注解進行數(shù)據(jù)驗證的方法

    java 自定義注解驗證可自己添加所需要的注解,下面這篇文章主要給大家介紹了關(guān)于JAVA中通過自定義注解進行數(shù)據(jù)驗證的相關(guān)資料,文中通過示例代碼介紹...

    Decouple6362021-05-25
  • Java教程淺談Java(SpringBoot)基于zookeeper的分布式鎖實現(xiàn)

    淺談Java(SpringBoot)基于zookeeper的分布式鎖實現(xiàn)

    這篇文章主要介紹了Java(SpringBoot)基于zookeeper的分布式鎖實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的...

    LJY_SUPER5742021-07-21
  • Java教程Java list.remove( )方法注意事項

    Java list.remove( )方法注意事項

    這篇文章主要介紹了Java list.remove( )方法注意事項,非常簡單易懂,需要的朋友可以參考下...

    妖久9552021-05-25
  • Java教程springboot ehcache 配置使用方法代碼詳解

    springboot ehcache 配置使用方法代碼詳解

    EhCache是一個比較成熟的Java緩存框架,Springboot對ehcache的使用非常支持,所以在Springboot中只需做些配置就可使用,且使用方式也簡易,今天給大家分享spri...

    m1719309529412912021-09-16
主站蜘蛛池模板: www.色.com| 精品久久久久久久久久久久 | 国产日韩一级片 | 日韩av专区| 免费在线看a| 在线观看av大片 | 亚洲自拍偷拍精品 | 国产精品久久久久久久久 | 韩国精品一区二区三区 | 免费看男女www网站入口在线 | 中文字幕第一页在线 | 精品99免费 | 91精品国产综合久久久久久漫画 | 国产精品亚洲视频 | 国产成人精品一区二区 | 九一午夜精品av | 久久国产欧美日韩精品 | 婷婷色综合| 超碰在线91| 久久久久久91亚洲精品中文字幕 | 欧美一级在线视频 | av免费在线观看网站 | 黄色免费美女网站 | 韩国一区二区视频 | 九九在线视频 | 久久爱综合 | 国产精品ssss在线亚洲 | 成人免费网站 | 成人1区2区 | 特级西西人体4444xxxx | 色五月激情综合网 | 亚洲精品资源在线观看 | 久久久精品影院 | 91精品国产综合久久香蕉922 | 久久av综合 | 国产精品一区二区三 | 亚洲精品视频在线观看网站 | 久久久精品欧美 | 色婷婷电影 | 91人人 | 91黄视频 |