Spring的FactoryBean的使用

FactoryBean

package com.wjz.spring;

import org.springframework.beans.factory.FactoryBean;

import com.wjz.demo.Foo;

@SuppressWarnings("rawtypes")
public class FooFactoryBean implements FactoryBean {

    @Override
    public Object getObject() throws Exception {
        Foo foo = new Foo();
        foo.setName("iss002");
        return foo;
    }

    @Override
    public Class getObjectType() {
        return Foo.class;
    }

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

}

demo

package com.wjz.demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringFactoryBeanDemo {
    
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-beans.xml");
        Foo foo = (Foo) context.getBean("fooFactoryBean");
        Foo foo2 = context.getBean("fooFactoryBean", Foo.class);
        System.out.println(foo.getName());
        System.out.println(foo2.getName());
    }

}

结果都是输出:iss002

原文地址:https://www.cnblogs.com/BINGJJFLY/p/9354398.html