Spring中注册组件方式总结

使用注解方式向Spring容器中注册组件,主要有三种方式,总结如下。

使用@ComponentScan注解

当要注入自己项目中的组件时,主要使用的就是这种组件注册方式。主要是通过扫描指定包下面含有特定注解的组件。

  • @Controller
  • @Service
  • @Component
  • @Repository

使用@Bean注解

当注册第三方包里的组件时,主要使用这种方式。把某个class显示地注册到Spring IOC容器中。

使用@Import注解

这种方式大量使用在Spring Boot项目中,提供了最大程度的灵活性。

  • 导入一个POJO到容器中作为bean

    class A {}
    
    @Import(A.class)
    public class MyConfig {
      // ...
    }
    
  • 通过 ImportSelector导入bean

    class MyImportSelector implements ImportSelector {
      // ...
    }
    
    @Import(MyImportSelector.class)
    public class MyConfig {
      // ...
    }
    
  • 通过BeanDefinitionRegistry注册bean

    class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
      // ...
    }
    
    @Import(MyImportBeanDefinitionRegistrar.class)
    public class MyConfig {
      // ...
    }
    
  • 使用Spring提供的FactoryBean

    public class ColorFactoryBean implements FactoryBean<Color> {
      // ...
    }
    
    @Configuration
    public class MyConfig {
      // 虽然这里的返回值是ColorFactoryBean,但是实际
      // 注册到容器中的bean的类型是Color
      @Bean
      public ColorFactoryBean colorFactoryBean() {
        return new ColorFactoryBean();
      }
    }
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。