环境搭建:创建maven工程,导入spring坐标,编写持久层接口和实现类,业务层接口和实现类。
在类路径下编写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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中
id 属性:对象的唯一标识。
class 属性:指定要创建对象的全限定类名
-->
<!-- 配置 service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
<!-- 配置 dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
</beans>
测试配置是否成功:
/**
* 模拟一个表现层
*/
public class Client {
public static void main(String[] args) {
//1.使用ApplicationContext接口,就是在获取spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.通过bean标签中的id获取容器中存储的对象
//因为ioc容器是Map<string,Object>形式,两种强转方式,普通强制转换和通过字节码参数
IAccountService as = (IAccountService) ac.getBean("accountService");
IAccountDao ad = ac.getBean("accountDao",IAccountDao.class);
System.out.println(as);
System.out.println(ad);
}
}