Alice52 / spring-5.2.x

spring source code
https://github.com/Alice52/spring-5.2.x/issues/2
0 stars 1 forks source link

[ioc] get componet from spring, such as ioc #37

Closed Alice52 closed 3 years ago

Alice52 commented 4 years ago

get ioc container

  1. configuration

    @Configuration
    public class IocContainer implements ApplicationContextAware {
       private ApplicationContext applicationContext;
    
       public ApplicationContext getApplicationContext() {
           return this.applicationContext;
       }
    
       @Override
       public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
           this.applicationContext = applicationContext;
       }
    
       @Bean
       public Person person() {
           return new Person();
       }
    }
  2. junit test

    @Slf4j
    public class IocContainerTest {
       private ApplicationContext applicationContext = new AnnotationConfigApplicationContext(IocContainer.class);
    
       @Test
       public void testGetIocContainer() {
           IocContainer contextBean = applicationContext.getBean(IocContainer.class);
           ApplicationContext applicationContext = contextBean.getApplicationContext();
    
           Person person0 = applicationContext.getBean(Person.class);
           log.info(String.valueOf(person0));
    
           Person person = applicationContext.getBean(Person.class);
           log.info(String.valueOf(person));
    
           Assert.isTrue(person0 == person);
           Assert.isFalse(applicationContext == contextBean);
       }
    }

xxAware: 获取 spring 底层的组件, 只需要自定义的组件实现 xxAware 接口

  1. ioc container: ApplicationContextAware
  2. bean factory: BeanFactoryAware
  3. ApplicationEventPublisherAware
  4. ServletContextAware
  5. MessageSourceAware
  6. ResourceLoaderAware
  7. NotificationPublisherAware
  8. EnvironmentAware
  9. EmbeddedValueResolverAware
  10. ImportAware
  11. ServletConfigAware
  12. LoadTimeWeaverAware
  13. BeanNameAware
  14. BeanClassLoaderAware

annotation-aware

Alice52 commented 4 years ago

inject to ioc[methods to inject]

  1. @Component/@Controller + @ComponentScan

    • 如果 @ComponentScan 使用自定义的方式或者指定包含某些类时[ASSIGNABLE_TYPE, REGEX, CUSTOM], 没有 @Component/@Controller 也可以成功注入 IOC
    • ANNOTATION 必须使用 @Component/@Controller 才能成功注入 IOC
  2. @Bean 将第三方包中的组件归置到 IOC 管理

  3. @Import

    • @Import
    • ImportSelector
    • ImportBeanDefinitionRegistrar
    • Spring FactoryBean: & 表示获取FactoryBean 本身; 否则会获取 FactoryBean 的 getObject 产生的对象