成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

工作中常用到的 Spring 依賴管理技術盤點

開發 后端
今天主要和大家分享一些在工作中可能會用到的Spring依賴注入,依賴查找方面的技術點整理,非常實用。

今天主要和大家分享一些在工作中可能會用到的Spring依賴注入,依賴查找方面的技術點整理,非常實用。

Spring依賴查找專題

單一類型查找

常見用法如下所示: 

  1. Object getBean(String name) throws BeansException;  
  2. <T> T getBean(Class<T> requiredType) throws BeansException;  
  3. <T> T getBean(String name, Class<T> requiredType) throws BeansException 

ObjectProvider

隨著Spring版本的升高,也開始出現了延遲查找的功能。當我們實際需要用到某個bean的時候才將其從容器中進行初始化并且提取出來。 

  1. <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);  
  2. <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType); 

Spring會返回一個ObjectProvider,當查詢的時候才會觸發bean的創建。

延遲查找的好處在于,如果一個bean需要注入到spring容器中,但是不希望太過早地去進行初始化,那么可以思考使用ObjectProvider的方式來進行初始化。

集合類型查找

Bean的名稱查詢 

  1. String[] getBeanNamesForType(@Nullable Class<?> type);   
  2. String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);  

獲取同類型Bean實例列表

  1. getBeansOfType(Class) 

按照注解去查詢 

  1. String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType);  
  2. Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;  
  3. <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws NoSuchBeanDefinitionException; 

使用依賴查找時候的一些小心得:

對于判斷一個bean是否存在,可以采用判斷其beandefinition是否存在,一般這樣不會觸發其中bean的初始化操作,例如:getBeanNamesForType。反觀getBeansOfType可能回觸發bean的初始化

層次性的bean查找

可能大多數人在實際使用Spring容器的時候對于層次性的bean做計算并沒有太多的實戰嘗試,這里我舉個例子:

例如說A容器中包含了Bean A,如果B容器繼承了A容器,那么按道理來說也應該能夠獲得Bean A資源,這種設計可以減少Bean的額外存儲。

如果你理解了我上邊所說的這個案例之后,再來看看下邊的這張圖可能就會有更加深入的理解了。

關于層次性的bean獲取,我這里給出一個小的demo供大家學習: 

  1. package org.idea.spring.look.up.factory;  
  2. import org.springframework.beans.factory.BeanFactory;  
  3. import org.springframework.beans.factory.HierarchicalBeanFactory;  
  4. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;  
  5. import org.springframework.context.ApplicationContext;  
  6. import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
  7. /**  
  8.  * 層次性的依賴查找 {@link org.springframework.beans.factory.HierarchicalBeanFactory}  
  9.  *  
  10.  * @Author idea  
  11.  * @Date created in 10:55 下午 2021/4/10  
  12.  */  
  13. public class SpringHierarchicalLookUpDemo {  
  14.     public static void main(String[] args) {  
  15.         AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();  
  16.         applicationContext.register(SpringHierarchicalLookUpDemo.class);  
  17.         applicationContext.refresh();  
  18.         ParentIocContainer parentIocContainer = new ParentIocContainer();  
  19.         ApplicationContext parentApplicationContext = parentIocContainer.getAndStartApplicationContext();  
  20.         // ConfigurableListableBeanFactory -> ConfigurableBeanFactory -> HierarchicalBeanFactory  
  21.         ConfigurableListableBeanFactory configurableListableBeanFactory = applicationContext.getBeanFactory();  
  22.         System.out.println("此時的父類BeanFactory為:" + configurableListableBeanFactory.getParentBeanFactory());  
  23.         configurableListableBeanFactory.setParentBeanFactory(parentApplicationContext);  
  24.         System.out.println("此時的父類BeanFactory為:" + configurableListableBeanFactory.getParentBeanFactory());  
  25.         ParentIocContainer.ParentBean parentBean = (ParentIocContainer.ParentBean) configurableListableBeanFactory.getBean("parentBean");  
  26.         System.out.println(parentBean);  
  27.         isContainedBean(configurableListableBeanFactory, "parentBean");  
  28.         displayContainsBean(configurableListableBeanFactory, "parentBean");  
  29.     }  
  30.     /**  
  31.      * 這里是子類可以獲取自己和父類層次內部的bean,如果是使用containsLocalBean方法的話就只能判斷當前所在層次的容器上下文  
  32.      *  
  33.      * @param beanFactory  
  34.      * @param beanName  
  35.      */  
  36.     public static void isContainedBean(HierarchicalBeanFactory beanFactory, String beanName) {  
  37.         System.out.println("getBean is " + beanFactory.getBean(beanName));  
  38.         System.out.printf("contained is [%s] ,beanFactory is [%s],beanName is [%s]\n", beanFactory.containsLocalBean(beanName), beanFactory, beanName);  
  39.     }  
  40.     /**  
  41.      * 查找關于父類容器內部的bean  
  42.      *  
  43.      * @param beanFactory  
  44.      * @param beanName  
  45.      */  
  46.     private static void displayContainsBean(HierarchicalBeanFactory beanFactory, String beanName) {  
  47.         System.out.printf("contained is [%s] ,beanFactory is [%s],beanName is [%s]\n", isContainedBeanInHoldApplication(beanFactory, beanName), beanFactory, beanName);  
  48.     }  
  49.     /**  
  50.      * 使用遞歸判斷 -- 自上到下判斷父類容器是否含有bean  
  51.      *  
  52.      * @param hierarchicalBeanFactory  
  53.      * @param beanName  
  54.      * @return  
  55.      */  
  56.     public static boolean isContainedBeanInHoldApplication(HierarchicalBeanFactory hierarchicalBeanFactory, String beanName) {  
  57.         BeanFactory parentBeanFactory = hierarchicalBeanFactory.getParentBeanFactory();  
  58.         if (parentBeanFactory instanceof HierarchicalBeanFactory) {  
  59.             HierarchicalBeanFactory parentHierarchicalBeanFactory = HierarchicalBeanFactory.class.cast(parentBeanFactory);  
  60.             if (isContainedBeanInHoldApplication(parentHierarchicalBeanFactory, beanName)) {  
  61.                 return true;  
  62.             }  
  63.         }  
  64.         return hierarchicalBeanFactory.containsBean(beanName);  
  65.     }  

對應的父類容器案例: 

  1. package org.idea.spring.look.up.factory;  
  2. import org.springframework.context.ApplicationContext;  
  3. import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
  4. /**  
  5.  * 父類ioc容器 這里面的ioc容器只包含有ParentBean這個類  
  6.  *  
  7.  * @Author idea  
  8.  * @Date created in 8:46 上午 2021/4/11  
  9.  */  
  10. public class ParentIocContainer {  
  11.     public static AnnotationConfigApplicationContext applicationContext = null 
  12.     class ParentBean {  
  13.         int id;  
  14.         public ParentBean(){  
  15.             System.out.println("this is no arg init");  
  16.         }  
  17.         @Override  
  18.         public String toString() {  
  19.             return "ParentBean{" +  
  20.                     "id=" + id +  
  21.                     '}';  
  22.         }  
  23.     }  
  24.     public ApplicationContext getAndStartApplicationContext(){  
  25.        applicationContext = new AnnotationConfigApplicationContext();  
  26.        applicationContext.register(ParentIocContainer.class);  
  27.        //需要支持無參構造函數  
  28.        applicationContext.registerBean("parentBean",ParentBean.class); 
  29.        applicationContext.refresh();  
  30.        return applicationContext;  
  31.     }  
  32.     public static void main(String[] args) {  
  33.         ParentIocContainer parentIocContainer = new ParentIocContainer();  
  34.         ApplicationContext applicationContext = parentIocContainer.getAndStartApplicationContext();  
  35.         String[] str = applicationContext.getBeanNamesForType(ParentBean.class);  
  36.         for (String beanName : str) {  
  37.             System.out.println(beanName);  
  38.         }  
  39.     } 

從這段代碼中可以看出,HierarchicalBeanFactory是一種常見的層次類BeanFactory,并且當我們需要判斷一個bean是否存在某個容器上下文中的時候,不妨可以試試使用BeanFacoty自帶的這個方法: 

  1. org.springframework.beans.factory.HierarchicalBeanFactory#containsLocalBean  
  2. /**  
  3.  * Return whether the local bean factory contains a bean of the given name,  
  4.  * ignoring beans defined in ancestor contexts.  
  5.  * <p>This is an alternative to {@code containsBean}, ignoring a bean  
  6.  * of the given name from an ancestor bean factory.  
  7.  * @param name the name of the bean to query  
  8.  * @return whether a bean with the given name is defined in the local factory  
  9.  * @see BeanFactory#containsBean 
  10.  */  
  11. boolean containsLocalBean(String name); 

Spring依賴注入專題

依賴注入的幾種模式

手動注入模式:

  •  寫XML的方式注入
  •  通過注解的方式注入
  •  通過API的方式去注入

自動注入的模式:

使用Autowiring的模式進行注入

常見的注入案例:

xml方式注入

例如通過xml配置文件對bean的屬性進行注入: 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  5.         https://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.     <bean id="malePerson" class="org.idea.spring.ioc.bean.Person" >  
  7.     <property name="id" value="1"></property>  
  8.     <property name="name" value="idea"></property>  
  9. </bean>  
  10.     <bean class="org.idea.spring.dependency.inject.setter.PersonHolder">  
  11.         <property name="person" ref="malePerson"></property>  
  12.     </bean>  
  13. </beans> 

對應的Person對象 

  1. @Data  
  2. @AllArgsConstructor  
  3. @NoArgsConstructor  
  4. public class Person {  
  5.     Integer id;  
  6.     String name; 

注解的方式注入

例如加入一個@Bean的注解進行注入容器 

  1. @Bean  
  2.   public PersonHolder personHolder(Person person){  
  3.       return new PersonHolder(person);  
  4.   } 

Spring容器內部的api注入

核心是利用了BeanDefinitionBuilder進行一個beanDefinition的構建,然后將這個beanDefinition給注入到Spring容器當中,上下文在啟動之后會將之前準備好的BeanDefinition機械能初始化創建。 

  1. import org.idea.spring.ioc.bean.Person;  
  2. import org.springframework.beans.factory.config.BeanDefinition;  
  3. import org.springframework.beans.factory.support.BeanDefinitionBuilder;  
  4. import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
  5. import org.springframework.context.annotation.Bean; 
  6. /**  
  7.  * 通過api的方式進行注入實現  
  8.  *  
  9.  * @Author idea  
  10.  * @Date created in 11:11 下午 2021/4/21  
  11.  */  
  12. public class ApiDependencyInjectDemo {  
  13.     @Bean  
  14.     public Person myPerson(){  
  15.         return new Person(1,"idea");  
  16.     }  
  17.     public static void main(String[] args) {  
  18.         AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();  
  19.         applicationContext.register(ApiDependencyInjectDemo.class);  
  20.         BeanDefinition personBeanDefinition = createUserBeanDefinition();  
  21.         applicationContext.registerBeanDefinition("personHolder",personBeanDefinition);  
  22.         applicationContext.refresh();  
  23.         PersonHolder personHolder = applicationContext.getBean(PersonHolder.class);  
  24.         System.out.println(personHolder.getPerson());  
  25.         applicationContext.close();  
  26.     }  
  27.     private static BeanDefinition createUserBeanDefinition() { 
  28.         BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(PersonHolder.class);  
  29.         //注意這里的add方法有多種類型,需要注意下細節點  
  30.         beanDefinitionBuilder.addPropertyReference("person","myPerson");  
  31.         return beanDefinitionBuilder.getBeanDefinition();  
  32.     }  

@Resource,@Autowire,@Qualifier模式注入

這兩類的注入在實際使用中頻率比較高:

  •  @Resource注解的注入會根據后邊的字段類型識別進行注入
  •  @Autowire則會根據bean的類型進行注入

這里有一段案例: 

  1. public class AnnotationDependencyInjectDemo {  
  2.     @Autowired  
  3.     private PersonHolder personHolder2;  
  4.     @Resource  
  5.     private PersonHolder personHolder;  
  6.     public static void main(String[] args) {  
  7.         AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();  
  8.         applicationContext.register(AnnotationDependencyInjectDemo.class);  
  9.         applicationContext.refresh();  
  10.         AnnotationDependencyInjectDemo annotationDependencyInjectDemo = applicationContext.getBean(AnnotationDependencyInjectDemo.class);  
  11.         System.out.println(annotationDependencyInjectDemo.personHolder);  
  12.         System.out.println(annotationDependencyInjectDemo.personHolder2);  
  13.         //這里面的兩個bean都是同一個,因為bean的作用域是一致相同的  
  14.         System.out.println(annotationDependencyInjectDemo.personHolder == annotationDependencyInjectDemo.personHolder2);  
  15.         applicationContext.close();  
  16.     }  
  17.     @Bean  
  18.     public PersonHolder personHolder(){  
  19.         return new PersonHolder(new Person(1,"idea"));  
  20.     }  

如果出現了一個接口對應多個實現類,但是代碼中使用的是@Autowire的方式進行依賴注入,此時可以通過新增@Qualifier注解的方式來實現依賴注入的效果。

單純從實際使用來說,我個人感覺@Resource = @Autowire + @Qualifier

依賴注入和依賴查找

在常見的業務開發當中,我們可能會使用到比較多的依賴注入注解,但是在一些基礎組件的開發中,我個人感覺使用依賴查找往往更加具有靈活性。

Spring內部的Bean有哪幾種

自定義的bean

例如業務系統中常見的XXXXDao,XXXXService

Spring容器中初始化構建好的Bean

例如Spring容器中的Enviorment對象

Spring容器內部的一些基礎服務對象

例如Spring容器內部的BeanFactory對象,這類Bean通常是無法通過getBean接口去直接獲取的。

Spring中的BeanDefinition對象

上邊我們有提及過到Spring內部提供了相關的Api供開發者進行靈活的依賴注入。但是當我們深入到具體細節進行分析之后,其實是可以發現BeanDefinition對象也是有不同類型差異的。

用戶自定義的BeanDeinition對象例如這樣一段代碼: 

  1. public class ApiDependencyInjectDemo {  
  2.     @Bean  
  3.     public Person myPerson(){  
  4.         return new Person(1,"idea");  
  5.     }  
  6.     public static void main(String[] args) {  
  7.         AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();  
  8.         applicationContext.register(ApiDependencyInjectDemo.class);  
  9.         BeanDefinition personBeanDefinition = createUserBeanDefinition();  
  10.         applicationContext.registerBeanDefinition("personHolder",personBeanDefinition);  
  11.         applicationContext.refresh();  
  12.         PersonHolder personHolder = applicationContext.getBean(PersonHolder.class);  
  13.         System.out.println(personHolder.getPerson());  
  14.         applicationContext.close();  
  15.     }  
  16.     private static BeanDefinition createUserBeanDefinition() {  
  17.         //spring官方比較推薦的一種注入方式  
  18.         BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(PersonHolder.class);  
  19.         //注意這里的add方法有多種類型,需要注意下細節點  
  20.         beanDefinitionBuilder.addConstructorArgReference("myPerson");  
  21.         return beanDefinitionBuilder.getBeanDefinition();  
  22.     }  

框架內部初始化定義好的BeanDefinition對象

具體體現在Spring容器進行初始化的時候,內部的refresh函數中有個prepareBeanFactory。

點進去這個函數,對它的源代碼進行深入解讀之后你會發現,其實內部已經注冊了一系列的BeanDefinition對象。

在容器初始化之后是否還能注冊Bean?

其實是可以的,下邊我通過使用BeanDefiniation的案例來和你一起分析一下: 

  1. package org.idea.spring.bean.source;  
  2. import org.springframework.beans.factory.config.BeanDefinition;  
  3. import org.springframework.beans.factory.support.BeanDefinitionBuilder;  
  4. import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
  5. import org.idea.spring.bean.beandefinitionbuilder.User;  
  6. /**  
  7.  * @Author idea  
  8.  * @Date created in 4:44 下午 2021/9/18  
  9.  */  
  10. public class AddBeanAfterRefreshDemo {  
  11.     public static void main(String[] args) {  
  12.         AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();  
  13.         annotationConfigApplicationContext.register(AddBeanAfterRefreshDemo.class);  
  14.         annotationConfigApplicationContext.refresh();  
  15.         try {  
  16.             User user0 = annotationConfigApplicationContext.getBean(User.class);  
  17.             System.out.println("user0 is " + user0);  
  18.         } catch (Exception b) {  
  19.             b.printStackTrace();  
  20.         }  
  21.         System.out.println("啟動后手動注入bean對象");  
  22.         BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);  
  23.         beanDefinitionBuilder.setScope("prototype"); 
  24.         beanDefinitionBuilder  
  25.                 .addPropertyValue("id", 2)  
  26.                 .addPropertyValue("name", "idea");  
  27.         annotationConfigApplicationContext.registerBeanDefinition("user", beanDefinitionBuilder.getBeanDefinition());  
  28.         //1)  
  29.         User user1 = (User) annotationConfigApplicationContext.getBean("user");  
  30.         BeanDefinition beanDefinition = annotationConfigApplicationContext.getBeanDefinition("user");  
  31.         System.out.println(beanDefinition.getScope());  
  32.         System.out.println(user1);  
  33.         annotationConfigApplicationContext.close();  
  34.     } 

注意,這里面如果將1)部分的代碼調整為: 

  1. User user1 = (User) annotationConfigApplicationContext.getBean(User.class); 

則不會實現容器啟動后注冊了對應的bean,但是依然查詢不到預期對象的效果。這是因為在Spring容器底層會有一個Map專門記錄不同的beanClass類型對應不同的beanName集合,從而導致第二次查詢的時候走了第一次查詢時候的緩存。代碼位于: 

  1. org.springframework.beans.factory.support.DefaultListableBeanFactory  
  2. /** Map of singleton and non-singleton bean names, keyed by dependency type. */  
  3.   private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);  

 

責任編輯:龐桂玉 來源: c知音
相關推薦

2021-10-27 17:57:35

設計模式場景

2019-08-07 16:50:38

SQLjoingroup

2020-05-13 21:09:10

JavaScript前端技術

2021-08-28 11:47:52

json解析

2023-11-26 17:47:00

數據分析

2017-11-21 15:34:15

Linux 開發開源

2024-04-28 11:22:18

2018-05-10 16:02:48

Android程序贈工具

2022-12-13 08:23:25

CSS前端漸變

2021-08-11 17:22:11

設計模式單例

2011-07-10 00:02:39

PHP

2010-10-08 16:32:59

MySQL語句

2024-01-05 09:13:35

2021-08-26 09:01:16

git 分布式Apache Subv

2022-02-07 20:29:13

物聯網數據傳輸單元DTU

2024-12-11 08:20:57

設計模式源碼

2019-09-10 16:54:23

程序員編程語言Java

2018-04-18 16:27:11

互聯網技術學習

2023-02-22 11:38:16

2021-11-03 15:15:21

Go重構技術
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 欧美一区二区在线播放 | 91精品久久久久久久99 | 91最新在线视频 | 人人九九精| 日韩av成人在线 | 中文字幕精品视频 | 国产亚洲精品精品国产亚洲综合 | 日本在线视频不卡 | 嫩草网| 综合视频在线 | 日本中文字幕在线观看 | 99re国产精品| 亚洲三级在线观看 | 蜜桃综合在线 | 亚洲中午字幕 | 亚洲精品99 | 日本在线中文 | 一区二区三区视频在线观看 | 日韩成人免费视频 | 干狠狠| 羞羞视频网站免费观看 | 亚洲 欧美 日韩在线 | 日本高清视频网站 | 国产在线视频一区 | 免费激情网站 | 久久综合一区 | 欧美一级大片 | 色香蕉在线 | 国产精品久久777777 | 伊人精品在线 | 日韩视频免费 | 久久久精品视频一区二区三区 | 欧美激情va永久在线播放 | 日日夜夜精品免费视频 | 精品一区二区三区在线观看国产 | 成人一区二区三区在线观看 | 亚洲国产aⅴ成人精品无吗 亚洲精品久久久一区二区三区 | 国产视频导航 | 欧美日本在线 | 国产精品免费一区二区三区四区 | 亚洲精品久久久久中文字幕欢迎你 |