Spring依赖注入:基于xml配置
基础接口 BeanFactory、ApplicationContext。
BeanFactory用于创建并管理、获取各种类的对象。
ApplicationContext从BeanFactory派生而来,并拥有更多实际功能。主要方法是getBean()获取Bean对象。
ApplicationContext可以从类路径加载配置文件(ClassPathXmlApplicationContext),也可以从文件系统中加载配置文件(FileSystemXmlApplicationContext)。
我们可以在xml文件中配置bean,然后通过ApplicationContext接口获取bean实例
Spring能够在applicationContext.xml中通过配置bean完成实例化对象,设置属性等。
1.配置bean
<bean id="dao" class="springTest.DaoImpl">
</bean>
实例化对象,相当于以下代码:
DaoImpl dao=new DaoImpl();
我们可以通过ApplicationContext接口获取对象,如下示:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
DaoImpl dao = (DaoImpl) context.getBean("dao");
ClassPathXmlApplicationContext会读取src文件的下一级中的对应xml文件
2.配置属性property
<bean id="dao" class="springTest.DaoImpl">
<property name="employee" value="lin"></property>
</bean>
设置属性,也就是setter,相当于以下代码:
DaoImpl dao=new DaoImpl();
dao.setEmployee=lin;
3.配置对象属性property
<bean id="dao" class="springTest.DaoImpl"></bean>
<bean id="serviceImpl" class="springTest.ServiceImpl">
<property name="dao" ref="dao"></property>
</bean>
设置对象属性,相当于以下代码:
DaoImpl dao=new DaoImpl();
ServiceImpl serviceImpl=new ServiceImpl();
serviceImpl.setDao=dao;
分类:
spring
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了