栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【spring源码】基于factoryMethod创建bean对象

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【spring源码】基于factoryMethod创建bean对象

案例:

1.定义Student类:

@Data
public class Student {
    private String name;
    private Integer age;

    public Student() {
    }

    public Student(String name) {
        this.name = name;
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

}

2.定义静态工厂方法/工厂实例方法:

public class StudentStaticFactory {

    public static Student getStudent(String name) {
        return new Student("悟饭");
    }

    public static Student getStudent(String name, int age) {

        return new Student("悟饭", 22);
    }
}

工厂实例方法

public class StudentInstanceFactory {

    public Student getStudent(String name) {
        Student student = new Student(name);
        return student;
    }
}

3.定义bean信息;分别定义使用静态工厂方法和实例工厂方法生成bean对象:



    
    
        
        
        
    

    
    
    
    
        
    

4.测试:

public class TestFactoryMethod {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("factoryMethod.xml");
        // 获取静态工厂方法中生成的bean对象
        Student stu = context.getBean("studentStatic", Student.class);
        System.out.println(stu);
        // 获取实例工厂方法生成bean对象
        Student student = context.getBean("student", Student.class);
        System.out.println(student);
    }
}



factoryMethod创建bean对象底层源码逻辑:

真正执行bean创建方法doCreateBean;所以这里主要梳理doCreateBean中执行工厂实例方法和工厂静态方法创建bean对象流程:

使用factoryMethod创建bean底层流程图:

instantiateUsingFactoryMethod底层实现逻辑:

instantiateUsingFactoryMethod方法实现流程图:

总结:
通过BeanDefinition属性factoryMethod创建bean对象是spring创建对象的5种方式之一;这种方式更为灵活,可以自行定义bean对象的生成方法;不局限于需要实现指定的接口和方法!关于BeanWrapperImpl包装对象设置了相关的类型转换服务;类型转换是创建bean对象封装到包装对象的重要作用!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/974223.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号