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;

 

posted on   乐之者v  阅读(254)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示