使用spring的IOC基于xml的方式解决程序耦合——快速入门

环境搭建:创建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);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值