日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
SpringBean的作用域scope你知道多少?如何自定義作用域?

環(huán)境:spring5.3.3

1 Scope作用

通過@Scope注解可以指定Bean的作用域,默認(rèn)情況都是單例的(ConfigurableBeanFactory.SCOPE_SINGLETON=singleton)

在創(chuàng)建bean實(shí)例時(shí)就是根據(jù)當(dāng)前定義BeanDefinition中的Scope來做不同的創(chuàng)建,源碼如下:

 
 
 
  1. protected  T doGetBean(
  2.             String name, @Nullable Class requiredType, @Nullable Object[] args, boolean typeCheckOnly)
  3.             throws BeansException {
  4.   String beanName = transformedBeanName(name);
  5.   Object bean;
  6.   // Eagerly check singleton cache for manually registered singletons.
  7.   Object sharedInstance = getSingleton(beanName);
  8.   if (sharedInstance != null && args == null) {
  9.     // other code
  10.   } else {
  11.     // other code
  12.     try {
  13.       RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  14.       checkMergedBeanDefinition(mbd, beanName, args);
  15.       // Guarantee initialization of beans that the current bean depends on.
  16.       // other code
  17.       // Create bean instance.
  18.       // 根據(jù)BeanDefinition中定義的Scope創(chuàng)建實(shí)例
  19.       // 判斷如果是單例
  20.       if (mbd.isSingleton()) {
  21.         // 如果是單例Bean會(huì)將Bean保存到緩存中singletonObjects  
  22.         sharedInstance = getSingleton(beanName, () -> {
  23.           try {
  24.             return createBean(beanName, mbd, args);
  25.           } catch (BeansException ex) {
  26.             destroySingleton(beanName);
  27.             throw ex;
  28.           }
  29.         });
  30.         bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  31.       }
  32.       // 判斷如果是原型(多例)
  33.       else if (mbd.isPrototype()) {
  34.         // It's a prototype -> create a new instance.
  35.         Object prototypeInstance = null;
  36.         try {
  37.           beforePrototypeCreation(beanName);
  38.           prototypeInstance = createBean(beanName, mbd, args);
  39.         } finally {
  40.           afterPrototypeCreation(beanName);
  41.         }
  42.         bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  43.       } 
  44.       else {
  45.         String scopeName = mbd.getScope();
  46.         if (!StringUtils.hasLength(scopeName)) {
  47.           throw new IllegalStateException("No scope name defined for bean 麓" + beanName + "'");
  48.         }
  49.         Scope scope = this.scopes.get(scopeName);
  50.         // 當(dāng)集合中也不存在時(shí)拋出異常  
  51.         if (scope == null) {
  52.           throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  53.         }
  54.         try {
  55.           Object scopedInstance = scope.get(beanName, () -> {
  56.             beforePrototypeCreation(beanName);
  57.             try {
  58.               return createBean(beanName, mbd, args);
  59.             } finally {
  60.               afterPrototypeCreation(beanName);
  61.             }
  62.           });
  63.           bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  64.         } catch (IllegalStateException ex) {
  65.           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);
  66.         }
  67.       }
  68.     } catch (BeansException ex) {
  69.       cleanupAfterBeanCreationFailure(beanName);
  70.       throw ex;
  71.     }
  72.   }
  73.   // other code
  74.   return (T) bean;
  75. }

從上面源碼看到分別判斷是了 是否是 Singleton及Proptotype,如果都不是則會(huì)從Map scopes中獲取。如果當(dāng)前你配置的@Scope不是singleton及prototype那么從scopes集合中?。ㄟ@個(gè)集合是通過AbstractBeanFactory#registerScope方法進(jìn)行注冊(cè)的,一般我們可以通過
BeanDefinitionRegistryPostProcessor進(jìn)行注冊(cè)),如果集合中也不存在那么就會(huì)拋出異常。如果存在就會(huì)執(zhí)行Scope#get方法

 
 
 
  1. Scope scope = this.scopes.get(scopeName);
  2. Object scopedInstance = scope.get(beanName, () -> {
  3.   beforePrototypeCreation(beanName);
  4.   try {
  5.     return createBean(beanName, mbd, args);
  6.   } finally {
  7.     afterPrototypeCreation(beanName);
  8.   }
  9. });

2 自定義Scope

自定義Scope

 
 
 
  1. public class CustomScope implements Scope {
  2.     
  3.   private Object target ;
  4.   @Override
  5.   public Object get(String name, ObjectFactory objectFactory) {
  6.     return target != null ? target : objectFactory.getObject() ;
  7.   }
  8.   // 如果調(diào)用了這個(gè)方法,那么下次在注入有@Scope("custom")的bean時(shí) 將會(huì)重寫調(diào)用objectFactory.getObject()方法。
  9.   @Override
  10.   public Object remove(String name) {
  11.     target = null ;
  12.     return "success" ;
  13.   }
  14.   @Override
  15.   public void registerDestructionCallback(String name, Runnable callback) {
  16.   }
  17.   @Override
  18.   public Object resolveContextualObject(String key) {
  19.     return null;
  20.   }
  21.   @Override
  22.   public String getConversationId() {
  23.     return null;
  24.   }
  25. }

注冊(cè)Scope

 
 
 
  1. @Component
  2. public class CustomScopeRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
  3.   @Override
  4.   public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  5.     beanFactory.registerScope("custom", new CustomScope()) ;
  6.   }
  7.   @Override
  8.   public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
  9.   }
  10. }

使用Scope

 
 
 
  1. @Component
  2. @Scope("custom")
  3. public class ApplyScopeBean {
  4. }

示例

 
 
 
  1. @RestController
  2. @RequestMapping("/refresh")
  3. @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  4. public class RefreshController implements ApplicationContextAware{
  5.   @Resource
  6.   private ApplyScopeBean scopeBean ;
  7.   @Resource
  8.   private CustomScope customScope ;
  9.   @GetMapping("/custom")
  10.   public String custom() {
  11.     return scopeBean.getCustom() ;
  12.   }
  13.   @GetMapping("/remove") 
  14.   public Object remove() {
  15.     return customScope.remove("applyScopeBean") ;
  16.   }  
  17. }

這里將Controller設(shè)置為多例,以便查看效果。交替執(zhí)行上面的接口,只要?jiǎng)h除了就會(huì)創(chuàng)建新的實(shí)例。

3 多例注入

如果一個(gè)Bean 設(shè)置了@Scope(value =

ConfigurableBeanFactory.SCOPE_PROTOTYPE) 當(dāng)這個(gè)Bean需要在一個(gè)單例Bean中被注入時(shí),需要如下配置才可

 
 
 
  1. @Component
  2. @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
  3. public class ApplyScopeBean {
  4. }

這樣才能正確地注入Bean,否則因?yàn)楸旧硎褂谜呤菃卫?,屬性只?huì)被初始化一次。也可以在每次使用前調(diào)用BeanFactory#getBean()。


網(wǎng)站題目:SpringBean的作用域scope你知道多少?如何自定義作用域?
網(wǎng)頁路徑:http://www.5511xx.com/article/djpejch.html