spring · 2019-12-15 0

Spring使用@Bean、@Import、FactoryBean注册Bean

创建Spring项目

若创建的是Java项目,向其加入Spring包;若创建的是Maven项目,添加如下依赖:

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

创建配置类

在类上加@Configuration注解,这个类就是配置类

@Configuration
public class BeanConfig {

}

一、@Bean

public class Red {
}

在配置类中,使用@Bean注解,注册Bean,把Red注册到容器中

@Configuration
public class BeanConfig {

    @Bean
    public Red red() {
        return new Red();
    }
}

二、@Import

1.@Import(组件)

@Import(组件),容器中就会自动注册这个组件

public class Green {
}

配置类:

@Configuration
@Import({Green.class})
public class BeanConfig {

    @Bean
    public Red red() {
        return new Red();
    }

}

2.ImportSelector

public class Blue {
}

ColorImportSelector实现ImportSelector接口,返回需要导入的组件的全类名数组

// 自定义逻辑和需要导入的组件
public class ColorImportSelector implements ImportSelector {

    // 返回值,就是要导入到容器中的组件全类名
    // AnnotationMetadata:当前标注@Import注解的类的所有注解信息
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[] {"com.example.entity.Blue"};
    }
}

配置类:

@Configuration
@Import({Green.class, ColorImportSelector.class})
public class BeanConfig {

    @Bean
    public Red red() {
        return new Red();
    }

}

3.ImportBeanDefinitionRegistrar

public class Gray {
}

ColorImportBeanDefinitionRegistrar实现ImportBeanDefinitionRegistrar接口,手动注册bean到容器中

public class ColorImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    // AnnotationMetadata 当前类的注解信息
    // BeanDefinitionRegistry BeanDefinition注册类
    // 把所有需要添加到容器中的bean,调用BeanDefinitionRegistry.registerBeanDefinition手工注册进来
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 指定Bean定义信息(Bean的类型,Bean...)
        RootBeanDefinition beanDefinition = new RootBeanDefinition(Gray.class);
        // 注册一个Bean,指定bean名
        registry.registerBeanDefinition("gray", beanDefinition);
    }
}

配置类:

@Configuration
@Import({Green.class, ColorImportSelector.class, ColorImportBeanDefinitionRegistrar.class})
public class BeanConfig {

    @Bean
    public Red red() {
        return new Red();
    }

}

三、FactoryBean

public class Yellow {
}

使用Spring提供的FactoryBean(工厂Bean),默认获取到工厂bean调用getObject创建的对象,要获取工厂Bean本身,我们需要给id前面加一个&

public class ColorFactoryBean implements FactoryBean<Yellow> {

    // 返回一个Yellow对象,这个对象会添加到容器中
    @Override
    public Yellow getObject() throws Exception {
        return new Yellow();
    }

    @Override
    public Class<?> getObjectType() {
        return Yellow.class;
    }

    // 返回true,表示单实例
    @Override
    public boolean isSingleton() {
        return true;
    }
}

配置类:

@Configuration
@Import({Green.class, ColorImportSelector.class, ColorImportBeanDefinitionRegistrar.class})
public class BeanConfig {

    @Bean
    public Red red() {
        return new Red();
    }

    @Bean
    public ColorFactoryBean colorFactoryBean(){
        return new ColorFactoryBean();
    }

}

四、测试

public class MyMain {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
        String[] definitionNames = applicationContext.getBeanDefinitionNames();
        for (String name : definitionNames) {
            Object bean = applicationContext.getBean(name);
            System.out.println("- - -");
            System.out.println("name: " + name);
            System.out.println("bean: " + bean.getClass());
        }

        System.out.println("\n- - - - - -\n");

        // 对于 FactoryBean
        List<String> list = Arrays.asList("colorFactoryBean", "&colorFactoryBean");
        for (String name : list) {
            Object bean = applicationContext.getBean(name);
            System.out.println("- - -");
            System.out.println("name: " + name);
            System.out.println("bean: " + bean.getClass());
        }
    }
}

结果:

DefaultListableBeanFactory 的 Map<String, Object> singletonObjects 中记录:

key: colorFactoryBean
value: ColorFactoryBean

- - -
name: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
bean: class org.springframework.context.annotation.ConfigurationClassPostProcessor
- - -
name: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
bean: class org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
- - -
name: org.springframework.context.annotation.internalCommonAnnotationProcessor
bean: class org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
- - -
name: org.springframework.context.event.internalEventListenerProcessor
bean: class org.springframework.context.event.EventListenerMethodProcessor
- - -
name: org.springframework.context.event.internalEventListenerFactory
bean: class org.springframework.context.event.DefaultEventListenerFactory
- - -
name: beanConfig
bean: class com.example.config.BeanConfig$$EnhancerBySpringCGLIB$$eb0e8d2e
- - -
name: com.example.entity.Green
bean: class com.example.entity.Green
- - -
name: com.example.entity.Blue
bean: class com.example.entity.Blue
- - -
name: red
bean: class com.example.entity.Red
- - -
name: colorFactoryBean
bean: class com.example.entity.Yellow
- - -
name: gray
bean: class com.example.entity.Gray

- - - - - -

- - -
name: colorFactoryBean
bean: class com.example.entity.Yellow
- - -
name: &colorFactoryBean
bean: class com.example.config.ColorFactoryBean

总结:

1.
@Configuration
public class BeanConfig {
}
生成
name: beanConfig
bean: class com.example.config.BeanConfig$$EnhancerBySpringCGLIB$$eb0e8d2e

2.
@Import({Green.class})
生成
name: com.example.entity.Green
bean: class com.example.entity.Green

3.
@Import({ColorImportSelector.class})
生成
name: com.example.entity.Blue
bean: class com.example.entity.Blue

4.
@Bean
public Red red() {
    return new Red();
}
生成
name: red
bean: class com.example.entity.Red

5.
@Bean
public ColorFactoryBean colorFactoryBean(){
    return new ColorFactoryBean();
}
生成
name: colorFactoryBean
bean: class com.example.entity.Yellow
name: &colorFactoryBean
bean: class com.example.config.ColorFactoryBean

6.
@Import({ColorImportBeanDefinitionRegistrar.class})
name: gray
bean: class com.example.entity.Gray