factorybean与beanfactory的区别

简单点来说factorybean就是获取它时需要在拿取这个bean的时候呢,我们需要在前面加上&符号,不然呢我们获取到的是factorybean中的getObject返回的bean。而beanfactory呢就是一个bean,就是东西比普通的bean更多,下面我们来新建一个factoryBean吧

@Component
public class ZzhFactoryBean implements FactoryBean {
    private String msg = "msg1,msg2,msg3";
    public void say() {
        System.out.println(" ZzhFactoryBean say");
    }

    @Override
    public Object getObject() throws Exception {
        ZzhConfigBean zzhConfigBean = new ZzhConfigBean();
        String[] m = msg.split(",");

        zzhConfigBean.setMsg1(m[0]);
        zzhConfigBean.setMsg2(m[1]);
        zzhConfigBean.setMsg3(m[2]);
        System.out.println(zzhConfigBean);
        return zzhConfigBean;
    }

    /**
     * @param
     * @method 返回值随意
     */
    @Override
    public Class<?> getObjectType() {
        return OtherBean.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

下面我们来进行测试喽,我们的factorybean中getObject方法返回的是ZzhConfigBean,这里面有三个私有属性msg1,msg2,msg3

public class ZzhConfigBean {
    private String msg1;
    private String msg2 ;
    private String msg3;
    public void say(){
        System.out.println(" ZzhBean say");
    }

    public void setMsg1(String msg1) {
        this.msg1 = msg1;
    }

    public void setMsg2(String msg2) {
        this.msg2 = msg2;
    }

    public void setMsg3(String msg3) {
        this.msg3 = msg3;
    }

    @Override
    public String toString() {
        return "ZzhBean{" +
                "msg1='" + msg1 + '\'' +
                ", msg2='" + msg2 + '\'' +
                ", msg3='" + msg3 + '\'' +
                '}';
    }
}

测试不加&直接拿取ZzhFactoryBean

  @Test
    public void test(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(config.class);
        // 拿到真正的工厂bean得加&
         //ZzhFactoryBean zzhFactoryBean = (ZzhFactoryBean)context.getBean("&zzhFactoryBean");

        //如果直接拿,拿到的是ZzhFactoryBean中的getObject返回的bean
        ZzhConfigBean zzhFactoryBean = (ZzhConfigBean)context.getBean("zzhFactoryBean");
        zzhFactoryBean.say();

    }

成功输出了经过我们getobject处理过的bean

factorybean与beanfactory的区别_第1张图片

测试加了&拿出来的bean,发现我们打印出来的是工厂bean中的say方法的结果
factorybean与beanfactory的区别_第2张图片
完整代码链接

你可能感兴趣的:(java,bean,redis,spring)