Spring或Springboot注册组件的四种方式

方式一:组件扫描

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

方式二:@Bean

  • 主要@Lazy只是配合 Bean的单例时候使用

方式三:@Import

  • 直接导入字节码
  • 实现ImportSelector接口,实现方法
  • 实现ImportBeanDefinitionRegistrar接口

方式四:FactoryBean

  • getObject();
  • getObjectType();
  • isSingleton();
  • 使用FactoryBean注册Bean的时候,直接使用getBean("myFactoryBean")获取的是Object方法中创建的对象,而不是MyFactoryBean本身的实例,如果真的像要获取MyFactoryBean的实例,那么需要在名称前 加 & 如: getBean("&myFactoryBean")

为什么获取FactoryBean本身的实例要添加&符号呢?

  • 因为BeanFactory中有定义
/**
	 * 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 = "&";
posted @ 2021-04-07 20:31  迁承_0204  阅读(271)  评论(0编辑  收藏  举报