自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

笑傲江湖,通過注解配置和包自動掃描的方式完成Bean對象的注冊

開發(fā) 前端
你經(jīng)歷過618和雙11嗎?你加入過大促時候那么多復雜的營銷活動賺幾毛錢嗎?你開發(fā)過連讀明白玩法都需要一周但只使用3天的大促需求嗎?

 [[413653]]

本文轉(zhuǎn)載自微信公眾號「bugstack蟲洞棧」,作者小傅哥。轉(zhuǎn)載本文請聯(lián)系bugstack蟲洞棧公眾號。

目錄

  • 一、前言
  • 二、目標
  • 三、方案
  • 四、實現(xiàn)
    • 1. 工程結(jié)構(gòu)
    • 2. 處理占位符配置
    • 3. 定義攔截注解
    • 4. 處理對象掃描裝配
    • 5. 解析xml中調(diào)用掃描
  • 五、測試
    • 1. 事先準備
    • 2. 屬性配置文件
    • 3. spring.xml 配置對象
    • 4. 單元測試(占位符)
    • 5. 單元測試(包掃描)
  • 六、總結(jié)

一、前言

忒復雜,沒等搞明白大促都過去了!

你經(jīng)歷過618和雙11嗎?你加入過大促時候那么多復雜的營銷活動賺幾毛錢嗎?你開發(fā)過連讀明白玩法都需要一周但只使用3天的大促需求嗎?有時候?qū)τ谟行┊a(chǎn)品的需求真的是太復雜了,復雜到開發(fā)、測試都需要在整個過程中不斷的學習最后才可能讀懂產(chǎn)品為啥這樣的玩,要是一個長期的活動可能也就算了,培養(yǎng)用戶心智嗎!但這一整套拉新、助力、激活、下單、投保、領券、消費、開紅包等等一連串的騷操作下來,如果在線上只用3天呢,或者是只用1天,那TM連參與的用戶都沒弄明白呢,活動就結(jié)束了,最后能打來什么樣好的數(shù)據(jù)呢?對于這樣流程復雜,估計連羊毛黨都看不上!!!

以上只是舉個例子,大部分時候并不會搞的這么惡心,評審也是過不去的!而同樣的道理用在程序設計開發(fā)和使用中也是一樣的,如果你把你的代碼邏輯實現(xiàn)的過于分散,讓外部調(diào)用方在使用的時候,需要調(diào)用你的接口多個和多次,還沒有消息觸達,只能定時自己輪訓你的接口查看訂單狀態(tài),每次還只能查10條,查多了你說不行,等等反人類的設計,都會給調(diào)用方帶來要干你的體會。

所以,如果我們能在完成目的的情況下,都是希望盡可能流程簡單、模式清晰、自動服務。那這在Spring的框架中也是有所體現(xiàn)的,這個框架的普及使用程度和它所能帶來的方便性是分不開的,而我們?nèi)绻茏龅饺绱说姆奖?,那肯定是一種好的設計和實現(xiàn)。

二、目標

其實到本章節(jié)我們已經(jīng)把關于 IOC 和 AOP 全部核心內(nèi)容都已經(jīng)實現(xiàn)完成了,只不過在使用上還有點像早期的 Spring 版本,需要一個一個在 spring.xml 中進行配置。這與實際的目前使用的 Spring 框架還是有蠻大的差別,而這種差別其實都是在核心功能邏輯之上建設的在更少的配置下,做到更簡化的使用。

這其中就包括:包的掃描注冊、注解配置的使用、占位符屬性的填充等等,而我們的目標就是在目前的核心邏輯上填充一些自動化的功能,讓大家可以學習到這部分的設計和實現(xiàn),從中體會到一些關于代碼邏輯的實現(xiàn)過程,總結(jié)一些編碼經(jīng)驗。

三、方案

首先我們要考慮??,為了可以簡化 Bean 對象的配置,讓整個 Bean 對象的注冊都是自動掃描的,那么基本需要的元素包括:掃描路徑入口、XML解析掃描信息、給需要掃描的Bean對象做注解標記、掃描Class對象摘取Bean注冊的基本信息,組裝注冊信息、注冊成Bean對象。那么在這些條件元素的支撐下,就可以實現(xiàn)出通過自定義注解和配置掃描路徑的情況下,完成 Bean 對象的注冊。除此之外再順帶解決一個配置中占位符屬性的知識點,比如可以通過 ${token} 給 Bean 對象注入進去屬性信息,那么這個操作需要用到 BeanFactoryPostProcessor,因為它可以處理 在所有的 BeanDefinition 加載完成后,實例化 Bean 對象之前,提供修改 BeanDefinition 屬性的機制 而實現(xiàn)這部分內(nèi)容是為了后續(xù)把此類內(nèi)容結(jié)合到自動化配置處理中。整體設計結(jié)構(gòu)如下圖:

結(jié)合bean的生命周期,包掃描只不過是掃描特定注解的類,提取類的相關信息組裝成BeanDefinition注冊到容器中。

在XmlBeanDefinitionReader中解析標簽,掃描類組裝BeanDefinition然后注冊到容器中的操作在ClassPathBeanDefinitionScanner#doScan中實現(xiàn)。

  • 自動掃描注冊主要是掃描添加了自定義注解的類,在xml加載過程中提取類的信息,組裝 BeanDefinition 注冊到 Spring 容器中。
  • 所以我們會用到 配置包路徑并在 XmlBeanDefinitionReader 解析并做相應的處理。這里的處理會包括對類的掃描、獲取注解信息等
  • 最后還包括了一部分關于 BeanFactoryPostProcessor 的使用,因為我們需要完成對占位符配置信息的加載,所以需要使用到 BeanFactoryPostProcessor 在所有的 BeanDefinition 加載完成后,實例化 Bean 對象之前,修改 BeanDefinition 的屬性信息。這一部分的實現(xiàn)也為后續(xù)處理關于占位符配置到注解上做準備

四、實現(xiàn)

1. 工程結(jié)構(gòu)

  1. small-spring-step-12 
  2. └── src 
  3.     ├── main 
  4.     │   └── java 
  5.     │       └── cn.bugstack.springframework 
  6.     │           ├── aop 
  7.     │           │   ├── aspectj 
  8.     │           │   │   └── AspectJExpressionPointcut.java 
  9.     │           │   │   └── AspectJExpressionPointcutAdvisor.java 
  10.     │           │   ├── framework  
  11.     │           │   │   ├── adapter 
  12.     │           │   │   │   └── MethodBeforeAdviceInterceptor.java 
  13.     │           │   │   ├── autoproxy 
  14.     │           │   │   │   └── MethodBeforeAdviceInterceptor.java 
  15.     │           │   │   ├── AopProxy.java 
  16.     │           │   │   ├── Cglib2AopProxy.java 
  17.     │           │   │   ├── JdkDynamicAopProxy.java 
  18.     │           │   │   ├── ProxyFactory.java 
  19.     │           │   │   └── ReflectiveMethodInvocation.java 
  20.     │           │   ├── AdvisedSupport.java 
  21.     │           │   ├── Advisor.java 
  22.     │           │   ├── BeforeAdvice.java 
  23.     │           │   ├── ClassFilter.java 
  24.     │           │   ├── MethodBeforeAdvice.java 
  25.     │           │   ├── MethodMatcher.java 
  26.     │           │   ├── Pointcut.java 
  27.     │           │   ├── PointcutAdvisor.java 
  28.     │           │   └── TargetSource.java 
  29.     │           ├── beans 
  30.     │           │   ├── factory 
  31.     │           │   │   ├── config 
  32.     │           │   │   │   ├── AutowireCapableBeanFactory.java 
  33.     │           │   │   │   ├── BeanDefinition.java 
  34.     │           │   │   │   ├── BeanFactoryPostProcessor.java 
  35.     │           │   │   │   ├── BeanPostProcessor.java 
  36.     │           │   │   │   ├── BeanReference.java 
  37.     │           │   │   │   ├── ConfigurableBeanFactory.java 
  38.     │           │   │   │   ├── InstantiationAwareBeanPostProcessor.java 
  39.     │           │   │   │   └── SingletonBeanRegistry.java 
  40.     │           │   │   ├── support 
  41.     │           │   │   │   ├── AbstractAutowireCapableBeanFactory.java 
  42.     │           │   │   │   ├── AbstractBeanDefinitionReader.java 
  43.     │           │   │   │   ├── AbstractBeanFactory.java 
  44.     │           │   │   │   ├── BeanDefinitionReader.java 
  45.     │           │   │   │   ├── BeanDefinitionRegistry.java 
  46.     │           │   │   │   ├── CglibSubclassingInstantiationStrategy.java 
  47.     │           │   │   │   ├── DefaultListableBeanFactory.java 
  48.     │           │   │   │   ├── DefaultSingletonBeanRegistry.java 
  49.     │           │   │   │   ├── DisposableBeanAdapter.java 
  50.     │           │   │   │   ├── FactoryBeanRegistrySupport.java 
  51.     │           │   │   │   ├── InstantiationStrategy.java 
  52.     │           │   │   │   └── SimpleInstantiationStrategy.java   
  53.     │           │   │   ├── support 
  54.     │           │   │   │   └── XmlBeanDefinitionReader.java 
  55.     │           │   │   ├── Aware.java 
  56.     │           │   │   ├── BeanClassLoaderAware.java 
  57.     │           │   │   ├── BeanFactory.java 
  58.     │           │   │   ├── BeanFactoryAware.java 
  59.     │           │   │   ├── BeanNameAware.java 
  60.     │           │   │   ├── ConfigurableListableBeanFactory.java 
  61.     │           │   │   ├── DisposableBean.java 
  62.     │           │   │   ├── FactoryBean.java 
  63.     │           │   │   ├── HierarchicalBeanFactory.java 
  64.     │           │   │   ├── InitializingBean.java 
  65.     │           │   │   ├── ListableBeanFactory.java 
  66.     │           │   │   └── PropertyPlaceholderConfigurer.java 
  67.     │           │   ├── BeansException.java 
  68.     │           │   ├── PropertyValue.java 
  69.     │           │   └── PropertyValues.java  
  70.     │           ├── context 
  71.     │           │   ├── annotation 
  72.     │           │   │   ├── ClassPathBeanDefinitionScanner.java  
  73.     │           │   │   ├── ClassPathScanningCandidateComponentProvider.java  
  74.     │           │   │   └── Scope.java  
  75.     │           │   ├── event 
  76.     │           │   │   ├── AbstractApplicationEventMulticaster.java  
  77.     │           │   │   ├── ApplicationContextEvent.java  
  78.     │           │   │   ├── ApplicationEventMulticaster.java  
  79.     │           │   │   ├── ContextClosedEvent.java  
  80.     │           │   │   ├── ContextRefreshedEvent.java  
  81.     │           │   │   └── SimpleApplicationEventMulticaster.java  
  82.     │           │   ├── support 
  83.     │           │   │   ├── AbstractApplicationContext.java  
  84.     │           │   │   ├── AbstractRefreshableApplicationContext.java  
  85.     │           │   │   ├── AbstractXmlApplicationContext.java  
  86.     │           │   │   ├── ApplicationContextAwareProcessor.java  
  87.     │           │   │   └── ClassPathXmlApplicationContext.java  
  88.     │           │   ├── ApplicationContext.java  
  89.     │           │   ├── ApplicationContextAware.java  
  90.     │           │   ├── ApplicationEvent.java  
  91.     │           │   ├── ApplicationEventPublisher.java  
  92.     │           │   ├── ApplicationListener.java  
  93.     │           │   └── ConfigurableApplicationContext.java 
  94.     │           ├── core.io 
  95.     │           │   ├── ClassPathResource.java  
  96.     │           │   ├── DefaultResourceLoader.java  
  97.     │           │   ├── FileSystemResource.java  
  98.     │           │   ├── Resource.java  
  99.     │           │   ├── ResourceLoader.java 
  100.     │           │   └── UrlResource.java 
  101.     │           ├── stereotype 
  102.     │           │   └── Component.java 
  103.     │           └── utils 
  104.     │               └── ClassUtils.java 
  105.     └── test 
  106.         └── java 
  107.             └── cn.bugstack.springframework.test 
  108.                 ├── bean 
  109.                 │   ├── IUserService.java 
  110.                 │   └── UserService.java 
  111.                 └── ApiTest.java 

工程源碼:公眾號「bugstack蟲洞?!?,回復:Spring 專欄,獲取完整源碼

在Bean的生命周期中自動加載包掃描注冊Bean對象和設置占位符屬性的類關系,如圖 14-2

圖 14-2

  • 整個類的關系結(jié)構(gòu)來看,其實涉及的內(nèi)容并不多,主要包括的就是 xml 解析類 XmlBeanDefinitionReader 對 ClassPathBeanDefinitionScanner#doScan 的使用。
  • 在 doScan 方法中處理所有指定路徑下添加了注解的類,拆解出類的信息:名稱、作用范圍等,進行創(chuàng)建 BeanDefinition 好用于 Bean 對象的注冊操作。
  • PropertyPlaceholderConfigurer 目前看上去像一塊單獨的內(nèi)容,后續(xù)會把這塊的內(nèi)容與自動加載 Bean 對象進行整合,也就是可以在注解上使用占位符配置一些在配置文件里的屬性信息。

2. 處理占位符配置

  1. public class PropertyPlaceholderConfigurer implements BeanFactoryPostProcessor { 
  2.  
  3.     /** 
  4.      * Default placeholder prefix: {@value} 
  5.      */ 
  6.     public static final String DEFAULT_PLACEHOLDER_PREFIX = "${"
  7.  
  8.     /** 
  9.      * Default placeholder suffix: {@value} 
  10.      */ 
  11.     public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}"
  12.  
  13.     private String location; 
  14.  
  15.     @Override 
  16.     public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { 
  17.         // 加載屬性文件 
  18.         try { 
  19.             DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); 
  20.             Resource resource = resourceLoader.getResource(location); 
  21.             Properties properties = new Properties(); 
  22.             properties.load(resource.getInputStream()); 
  23.  
  24.             String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames(); 
  25.             for (String beanName : beanDefinitionNames) { 
  26.                 BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); 
  27.  
  28.                 PropertyValues propertyValues = beanDefinition.getPropertyValues(); 
  29.                 for (PropertyValue propertyValue : propertyValues.getPropertyValues()) { 
  30.                     Object value = propertyValue.getValue(); 
  31.                     if (!(value instanceof String)) continue
  32.                     String strVal = (String) value; 
  33.                     StringBuilder buffer = new StringBuilder(strVal); 
  34.                     int startIdx = strVal.indexOf(DEFAULT_PLACEHOLDER_PREFIX); 
  35.                     int stopIdx = strVal.indexOf(DEFAULT_PLACEHOLDER_SUFFIX); 
  36.                     if (startIdx != -1 && stopIdx != -1 && startIdx < stopIdx) { 
  37.                         String propKey = strVal.substring(startIdx + 2, stopIdx); 
  38.                         String propVal = properties.getProperty(propKey); 
  39.                         buffer.replace(startIdx, stopIdx + 1, propVal); 
  40.                         propertyValues.addPropertyValue(new PropertyValue(propertyValue.getName(), buffer.toString())); 
  41.                     } 
  42.                 } 
  43.             } 
  44.         } catch (IOException e) { 
  45.             throw new BeansException("Could not load properties", e); 
  46.         } 
  47.     } 
  48.  
  49.     public void setLocation(String location) { 
  50.         this.location = location; 
  51.     } 
  52.  

依賴于 BeanFactoryPostProcessor 在 Bean 生命周期的屬性,可以在 Bean 對象實例化之前,改變屬性信息。所以這里通過實現(xiàn) BeanFactoryPostProcessor 接口,完成對配置文件的加載以及摘取占位符中的在屬性文件里的配置。

這樣就可以把提取到的配置信息放置到屬性配置中了,buffer.replace(startIdx, stopIdx + 1, propVal); propertyValues.addPropertyValue

3. 定義攔截注解

cn.bugstack.springframework.context.annotation.Scope

  1. @Target({ElementType.TYPE, ElementType.METHOD}) 
  2. @Retention(RetentionPolicy.RUNTIME) 
  3. @Documented 
  4. public @interface Scope { 
  5.  
  6.     String value() default "singleton"
  7.  
  • 用于配置作用域的自定義注解,方便通過配置Bean對象注解的時候,拿到Bean對象的作用域。不過一般都使用默認的 singleton

cn.bugstack.springframework.stereotype.Component

  1. @Target(ElementType.TYPE) 
  2. @Retention(RetentionPolicy.RUNTIME) 
  3. @Documented 
  4. public @interface Component { 
  5.  
  6.     String value() default ""
  7.  

Component 自定義注解大家都非常熟悉了,用于配置到 Class 類上的。除此之外還有 Service、Controller,不過所有的處理方式基本一致,這里就只展示一個 Component 即可。

4. 處理對象掃描裝配

cn.bugstack.springframework.context.annotation.ClassPathScanningCandidateComponentProvider

  1. public class ClassPathScanningCandidateComponentProvider { 
  2.  
  3.     public Set<BeanDefinition> findCandidateComponents(String basePackage) { 
  4.         Set<BeanDefinition> candidates = new LinkedHashSet<>(); 
  5.         Set<Class<?>> classes = ClassUtil.scanPackageByAnnotation(basePackage, Component.class); 
  6.         for (Class<?> clazz : classes) { 
  7.             candidates.add(new BeanDefinition(clazz)); 
  8.         } 
  9.         return candidates; 
  10.     } 
  11.  
  • 這里先要提供一個可以通過配置路徑 basePackage=cn.bugstack.springframework.test.bean,解析出 classes 信息的工具方法 findCandidateComponents,通過這個方法就可以掃描到所有 @Component 注解的 Bean 對象了。

cn.bugstack.springframework.context.annotation.ClassPathBeanDefinitionScanner

  1. public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider { 
  2.  
  3.     private BeanDefinitionRegistry registry; 
  4.  
  5.     public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) { 
  6.         this.registry = registry; 
  7.     } 
  8.  
  9.     public void doScan(String... basePackages) { 
  10.         for (String basePackage : basePackages) { 
  11.             Set<BeanDefinition> candidates = findCandidateComponents(basePackage); 
  12.             for (BeanDefinition beanDefinition : candidates) { 
  13.                 // 解析 Bean 的作用域 singleton、prototype 
  14.                 String beanScope = resolveBeanScope(beanDefinition); 
  15.                 if (StrUtil.isNotEmpty(beanScope)) { 
  16.                     beanDefinition.setScope(beanScope); 
  17.                 } 
  18.                 registry.registerBeanDefinition(determineBeanName(beanDefinition), beanDefinition); 
  19.             } 
  20.         } 
  21.     } 
  22.  
  23.     private String resolveBeanScope(BeanDefinition beanDefinition) { 
  24.         Class<?> beanClass = beanDefinition.getBeanClass(); 
  25.         Scope scope = beanClass.getAnnotation(Scope.class); 
  26.         if (null != scope) return scope.value(); 
  27.         return StrUtil.EMPTY; 
  28.     } 
  29.  
  30.     private String determineBeanName(BeanDefinition beanDefinition) { 
  31.         Class<?> beanClass = beanDefinition.getBeanClass(); 
  32.         Component component = beanClass.getAnnotation(Component.class); 
  33.         String value = component.value(); 
  34.         if (StrUtil.isEmpty(value)) { 
  35.             value = StrUtil.lowerFirst(beanClass.getSimpleName()); 
  36.         } 
  37.         return value; 
  38.     } 
  39.  

ClassPathBeanDefinitionScanner 是繼承自 ClassPathScanningCandidateComponentProvider 的具體掃描包處理的類,在 doScan 中除了獲取到掃描的類信息以后,還需要獲取 Bean 的作用域和類名,如果不配置類名基本都是把首字母縮寫。

5. 解析xml中調(diào)用掃描

cn.bugstack.springframework.beans.factory.xml.XmlBeanDefinitionReader

  1. public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { 
  2.  
  3.     protected void doLoadBeanDefinitions(InputStream inputStream) throws ClassNotFoundException, DocumentException { 
  4.         SAXReader reader = new SAXReader(); 
  5.         Document document = reader.read(inputStream); 
  6.         Element root = document.getRootElement(); 
  7.  
  8.         // 解析 context:component-scan 標簽,掃描包中的類并提取相關信息,用于組裝 BeanDefinition 
  9.         Element componentScan = root.element("component-scan"); 
  10.         if (null != componentScan) { 
  11.             String scanPath = componentScan.attributeValue("base-package"); 
  12.             if (StrUtil.isEmpty(scanPath)) { 
  13.                 throw new BeansException("The value of base-package attribute can not be empty or null"); 
  14.             } 
  15.             scanPackage(scanPath); 
  16.         } 
  17.         
  18.         // ... 省略其他 
  19.              
  20.         // 注冊 BeanDefinition 
  21.         getRegistry().registerBeanDefinition(beanName, beanDefinition); 
  22.     } 
  23.  
  24.     private void scanPackage(String scanPath) { 
  25.         String[] basePackages = StrUtil.splitToArray(scanPath, ','); 
  26.         ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(getRegistry()); 
  27.         scanner.doScan(basePackages); 
  28.     } 
  29.  
  • 關于 XmlBeanDefinitionReader 中主要是在加載配置文件后,處理新增的自定義配置屬性 component-scan,解析后調(diào)用 scanPackage 方法,其實也就是我們在 ClassPathBeanDefinitionScanner#doScan 功能。
  • 另外這里需要注意,為了可以方便的加載和解析xml,XmlBeanDefinitionReader 已經(jīng)全部替換為 dom4j 的方式進行解析處理。

五、測試

1. 事先準備

  1. @Component("userService"
  2. public class UserService implements IUserService { 
  3.  
  4.     private String token; 
  5.  
  6.     public String queryUserInfo() { 
  7.         try { 
  8.             Thread.sleep(new Random(1).nextInt(100)); 
  9.         } catch (InterruptedException e) { 
  10.             e.printStackTrace(); 
  11.         } 
  12.         return "小傅哥,100001,深圳"
  13.     } 
  14.  
  15.     public String register(String userName) { 
  16.         try { 
  17.             Thread.sleep(new Random(1).nextInt(100)); 
  18.         } catch (InterruptedException e) { 
  19.             e.printStackTrace(); 
  20.         } 
  21.         return "注冊用戶:" + userName + " success!"
  22.     } 
  23.  
  24.     @Override 
  25.     public String toString() { 
  26.         return "UserService#token = { " + token + " }"
  27.     } 
  28.  
  29.     public String getToken() { 
  30.         return token; 
  31.     } 
  32.  
  33.     public void setToken(String token) { 
  34.         this.token = token; 
  35.     } 

給 UserService 類添加一個自定義注解 @Component("userService") 和一個屬性信息 String token。這是為了分別測試包掃描和占位符屬性。

2. 屬性配置文件

  1. token=RejDlI78hu223Opo983Ds 

這里配置一個 token 的屬性信息,用于通過占位符的方式進行獲取

3. spring.xml 配置對象

  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.        xmlns:context="http://www.springframework.org/schema/context" 
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans 
  6.           http://www.springframework.org/schema/beans/spring-beans.xsd 
  7.    http://www.springframework.org/schema/context"> 
  8.  
  9.     <bean class="cn.bugstack.springframework.beans.factory.PropertyPlaceholderConfigurer"
  10.         <property name="location" value="classpath:token.properties"/> 
  11.     </bean> 
  12.  
  13.     <bean id="userService" class="cn.bugstack.springframework.test.bean.UserService"
  14.         <property name="token" value="${token}"/> 
  15.     </bean> 
  16.  
  17. </beans> 
  • 加載 classpath:token.properties 設置占位符屬性值 ${token}

spring-scan.xml

  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.        xmlns:context="http://www.springframework.org/schema/context" 
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans 
  6.           http://www.springframework.org/schema/beans/spring-beans.xsd 
  7.    http://www.springframework.org/schema/context"> 
  8.  
  9.     <context:component-scan base-package="cn.bugstack.springframework.test.bean"/> 
  10.  
  11. </beans> 

添加 component-scan 屬性,設置包掃描根路徑

4. 單元測試(占位符)

  1. @Test 
  2. public void test_property() { 
  3.     ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring-property.xml"); 
  4.     IUserService userService = applicationContext.getBean("userService", IUserService.class); 
  5.     System.out.println("測試結(jié)果:" + userService); 

測試結(jié)果

  1. 測試結(jié)果:UserService#token = { RejDlI78hu223Opo983Ds } 
  2.  
  3. Process finished with exit code 0 

通過測試結(jié)果可以看到 UserService 中的 token 屬性已經(jīng)通過占位符的方式設置進去配置文件里的 token.properties 的屬性值了。

5. 單元測試(包掃描)

  1. @Test 
  2. public void test_scan() { 
  3.     ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring-scan.xml"); 
  4.     IUserService userService = applicationContext.getBean("userService", IUserService.class); 
  5.     System.out.println("測試結(jié)果:" + userService.queryUserInfo()); 

測試結(jié)果

  1. 測試結(jié)果:小傅哥,100001,深圳 
  2.  
  3. Process finished with exit code 0 

通過這個測試結(jié)果可以看出來,現(xiàn)在使用注解的方式就可以讓 Class 注冊完成 Bean 對象了。

六、總結(jié)

通過整篇的內(nèi)容實現(xiàn)可以看出來,目前的功能添加其實已經(jīng)不復雜了,都是在 IOC 和 AOP 核心的基礎上來補全功能。這些補全的功能也是在完善 Bean 的生命周期,讓整個功能使用也越來越容易。

在你不斷的實現(xiàn)著 Spring 的各項功能時,也可以把自己在平常使用 Spring 的一些功能想法融入進來,比如像 Spring 是如何動態(tài)切換數(shù)據(jù)源的,線程池是怎么提供配置的,這些內(nèi)容雖然不是最基礎的核心范圍,但也非常重要。

可能有些時候這些類實現(xiàn)的內(nèi)容對新人來說比較多,可以一點點動手實現(xiàn)逐步理解,在把一些稍微較有難度的內(nèi)容實現(xiàn)后,其實后面也就沒有那么難理解了。

 

責任編輯:武曉燕 來源: bugstack蟲洞棧
相關推薦

2012-11-05 09:53:27

云存儲SaaSPaaS

2016-02-26 12:05:06

華為

2010-07-16 10:22:19

金山雷軍

2011-09-22 09:26:49

PowerAIX

2011-07-14 10:51:40

飛視美視頻會議

2011-06-20 11:02:35

激光打印機推薦

2011-10-14 10:51:05

桌面虛擬化服務器

2021-08-04 11:39:17

Bean對象配置

2010-05-13 14:59:23

移動互聯(lián)網(wǎng)新浪模式

2023-05-10 08:29:28

Spring配置原理

2012-04-11 15:06:48

投影機評測

2023-09-28 09:17:18

SpringBootBean

2023-03-08 09:59:39

SpringBean注入

2024-07-31 11:26:05

反射BeanXML

2023-12-01 08:00:57

微信運動SpringBean

2009-07-01 14:09:24

Servlet和BeaJSP

2019-07-02 11:01:35

SpringBean配置

2023-04-28 12:37:59

Spring@Bean使用方式

2023-04-23 09:50:50

@BeanSpring

2015-09-16 11:13:51

ChefWindows集群運維
點贊
收藏

51CTO技術棧公眾號