DefaultListableBeanFactory+ GenericBeanDefinition

定义与用途:

  • 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}

posted @   文采杰出  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示