首页 > 其他分享 >DefaultListableBeanFactory+ GenericBeanDefinition

DefaultListableBeanFactory+ GenericBeanDefinition

时间:2024-05-28 14:44:51浏览次数:15  
标签:GenericBeanDefinition birth Bean Student DefaultListableBeanFactory new

定义与用途:

  • GenericBeanDefinition:它是Spring框架中用于定义通用Bean的一个类。它继承自抽象类AbstractBeanDefinition,并增加了一个成员属性parentName。这个类主要用于存储Bean的配置信息,包括Bean的类名、作用域、属性等。
  • DefaultListableBeanFactory:它是Spring IoC容器的一个核心实现类,实现了BeanFactory接口。它的主要任务是管理Bean的生命周期,包括Bean的创建、初始化和销毁。此外,它还提供了自动装配、事件发布、后处理器支持等功能。

总结: GenericBeanDefinition主要负责Bean的定义和配置信息的存储,而DefaultListableBeanFactory则负责根据这些定义创建和管理Bean实例。它们在Spring框架中协同工作,共同实现IoC容器的功能。
案例:

  • 实体类:
public class Student {
    private Date birth;

  /*  public void setBirth(Date birth) {
        this.birth = birth;
    }*/

    public void setBirth(String birthStr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        this.birth = sdf.parse(birthStr);
    }

    @Override
    public String toString() {
        return "Student{" +
                "birth=" + birth +
                '}';
    }
}
  • 测试,没有通过xml注册哦
    @Test
    public void testRegisterBean() throws ParseException {
        //自己new的对象
   /*     Student student = new Student();
        System.out.println(student);
        System.out.println("=====");*/

        // 创建 DefaultListableBeanFactory 实例
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

        //注册bean定义
        GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
        genericBeanDefinition.setBeanClassName("com.powernode.spring6.bean.Student");
//setScope为空模式是singleton,也可以填BeanDefinition.SCOPE_PROTOTYPE
        genericBeanDefinition.setScope("");

        beanFactory.registerBeanDefinition("student",genericBeanDefinition);

        Student student1 = (Student) beanFactory.getBean("student");

        student1.setBirth("2023-03-15");
        System.out.println(student1);
    }

输出结果: Student{birth=Wed Mar 15 00:00:00 CST 2023}

标签:GenericBeanDefinition,birth,Bean,Student,DefaultListableBeanFactory,new
From: https://www.cnblogs.com/DuWenjie/p/18217984

相关文章