Springboot 实现FactoryBean接口注入Bean

前面的博客中我们了解了如何使用@Bean注解注入Bean,在这篇博客我们将通过创建一个实现FactoryBean接口的类去注入定制的Bean。

    项目结构: 创建MyFactoryBean类,并实现FactoryBean接口
import com.michael.annotation.demo.POJO.Department;
import org.springframework.beans.factory.FactoryBean;

//1. 这里的接口泛型参数为要注入Bean的类型
public class MyFactoryBean implements FactoryBean<Department> {
          
   
    //2.重写的第一个方法返回Bean的实例
    @Override
    public Department getObject() throws Exception {
          
   
        return new Department();
    }

    //3.重写的第二个方法返回Bean的类型
    @Override
    public Class<?> getObjectType() {
          
   
        return Department.class;
    }

    //4.重写的第三个方法返回一个boolean值,决定该Bean的类型是单例还是多实例。这里返回true,为单例。
    @Override
    public boolean isSingleton() {
          
   
        return true;
    }
}
    把MyFactoryBean类的Bean注入容器,即实现了把Department类Bean注入容器。
import com.michael.annotation.demo.POJO.Person;
import com.michael.annotation.demo.POJO.Student;
import org.springframework.context.annotation.*;

@Configuration
@Import({
          
   Student.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
public class MyConfig {
          
   
    @Bean
    public Person person(){
          
   
        return new Person("Michael", 19);
    }

    @Bean
    public MyFactoryBean DepartmentBean(){
          
   //这里的方法名称是Department类Bean的ID
        return new MyFactoryBean();
    }
}
    测试代码:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import static java.lang.System.out;
@SpringBootApplication
public class DemoApplication {
          
   

    public static void main(String[] args) {
          
   
        ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);

         for(String name : applicationContext.getBeanDefinitionNames()){
          
   
            if(!name.contains("."))
                out.println(name);
        }

         //按照ID获取Department类的Bean
         out.println(applicationContext.getBean("DepartmentBean"));
        //按照ID:"&Department"获取MyFactoryBean类的Bean
        out.println(applicationContext.getBean("&DepartmentBean"));
    }
}
    输出:
demoApplication
test
myConfig
personService
person
DepartmentBean
Class
propertySourcesPlaceholderConfigurer
taskExecutorBuilder
applicationTaskExecutor
taskSchedulerBuilder
com.michael.annotation.demo.POJO.Department@4196c360
com.michael.annotation.demo.configuration.MyFactoryBean@41294f8
    观察输出,可以发现Department类的Bean被注入了容器。
经验分享 程序员 微信小程序 职场和发展