方式一:组件扫描
- @Controller
- @Repository
- @Service
- @Component
方式二:@Bean
方式三:@Import
- 直接导入字节码
- 实现ImportSelector接口,实现方法
- 实现ImportBeanDefinitionRegistrar接口
方式四:FactoryBean
- getObject();
- getObjectType();
- isSingleton();
- 使用FactoryBean注册Bean的时候,直接使用getBean("myFactoryBean")获取的是Object方法中创建的对象,而不是MyFactoryBean本身的实例,如果真的像要获取MyFactoryBean的实例,那么需要在名称前 加 & 如: getBean("&myFactoryBean")
为什么获取FactoryBean本身的实例要添加&符号呢?
/**
* Used to dereference a {@link FactoryBean} instance and distinguish it from
* beans <i>created</i> by the FactoryBean. For example, if the bean named
* {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}
* will return the factory, not the instance returned by the factory.
*/
String FACTORY_BEAN_PREFIX = "&";