六、【接口】Spring接口FactoryBean

FactoryBean是用来向容器中注入Bean的接口。而BeanFactory是从容器中取Bean的接口。

  1. 定义Fish实体类
/**
 * @author zhangjianbing
 * @date 2020年9月23日
 */
@Data
public class Fish {

    private String name;

    private int age;

    public Fish(){}

    public Fish(String name, int age) {
        this.name = name;
        this.age = age;
    }

}
  1. 实现FactoryBean来注入实体类
/**
 * @author zhangjianbing
 * @date 2020年9月23日
 */
public class FactoryBeanRegist implements FactoryBean<Fish> {

    @Override
    public Fish getObject() throws Exception {
        return new Fish();
    }

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

    @Override
    public boolean isSingleton() {
        return true;
    }
}
  1. 编写配置类
/**
 * @author zhangjianbing
 * @date 2020年9月23日
 */
@Configuration
public class FactoryBeanConfig {

    @Bean
    public FactoryBeanRegist getBean() {
        return new FactoryBeanRegist();
    }

}
  1. 测试
/**
 * @author zhangjianbing
 * @date 2020年9月23日
 */
public class Test01 {

    @Test
    public void test() {

        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(FactoryBeanConfig.class);
        // 不加"&"获取到的是FactoryBean中的实例
        Object getBean1 = ac.getBean("getBean");
        // 加"&"获取到的是实现了FactoryBean接口的FactoryBeanRegist本身
        Object getBean2 = ac.getBean("&getBean");
        System.out.println(getBean1.getClass());
        System.out.println(getBean2.getClass());

    }

}
  1. 测试结果
class com.nmys.story.springCore.springioc.importBean.Fish
class com.nmys.story.springCore.springioc.factoryBean.FactoryBeanRegist
posted @ 2020-09-24 08:29  在谷歌上百度  阅读(190)  评论(0编辑  收藏  举报