spring------FactoryBean自定义实例化bean的构造方式

前言

今天我们实现一个小的功能,spring中通过配置bean标签,然后就可以加载解析了,但由的时候,某个bean我们希望通过自己定义的方法来构造对象,这样我们可以加入自己的一些扩展。

创建实体类 Teacher

public class Teacher {
    private String nane;
    private int age;
    public String getNane() {
        return nane;
    }

    public void setNane(String nane) {
        this.nane = nane;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Teacher(String nane, int age) {
        this.nane = nane;
        this.age = age;
    }

    public Teacher() {
    }
}

xml 文件



    
    


student 是正常的注入,teacher 用我们自己定义的,str 是我们自己定义属性,

TeacherFactoryBean

public class TeacherFactoryBean implements FactoryBean {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public Teacher getObject() throws Exception {
        if(!StringUtils.isEmpty(this.str)) {
            String[] info = str.split(",");
            Teacher teacher = new Teacher();
            teacher.setNane(info[0]);
            teacher.setAge(Integer.parseInt(info[1]));
            return teacher;
        }
        return null;
    }

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

测试

    public static void main(String[] args) {
        BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("ApplicationContext.xml"));
        Teacher teacher = (Teacher) beanFactory.getBean("teacher");
        System.out.println(teacher);
        TeacherFactoryBean obj = beanFactory.getBean("&teacher",TeacherFactoryBean.class);
        System.out.println(obj.getStr());
    }

com.example.spring.Teacher@29ca901e
旭东,23

总结

这种方式的对象来源是 TeacherFactoryBean 的getObject()方法,特别注意的是: getBean获取的是 Teacher对象,如果要获取TeacherFactoryBean ,则要在getBean的参数前边加上 “&“。

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