使用注解方式向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(); } }