resources下的bean.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean> <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean> </beans>Client.java
public class Client { public static void main(String[] args) { //IAccountService accountService=new AccountServiceImpl(); //1、获取容器核心对象 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); IAccountService accountService=(IAccountService)ac.getBean("accountService"); IAccountDao accountDao=ac.getBean("accountDao",IAccountDao.class); accountService.saveAccount(); } }整个的过程非常简单,和我们工厂模式要做的其实是一样的,只不过我们读取配置文件,创建对象,并存入map的过程全都让spring干了。
我们只需要创建配置文件,把该配的信息交给spring,并且得到核心容器,再根据唯一标志取出我们想要的对象就可以了。