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;
原文地址:https://www.cnblogs.com/expiator/p/6824223.html