2.spring的IOC和DI

1.创建一个子项目

在这里插入图片描述
applicationContext.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">
    <!-- 通过spring来创建对象,在spring称为bean
         id等价于原来new对象的句柄
     -->
    <bean id="hello" class="com.wh.entity.Hello">
        <!-- set方法 属性注入值 -->
        <property name="str" value="Spring你好!"></property>
    </bean>
</beans>

2.测试

在这里插入图片描述

3.ClassPathXmlApplicationContext源码分析

在这里插入图片描述
在这里插入图片描述
refresh()方法就是spring容器的入口,核心方法
下面的文章可以更深层次的理解该过程
https://blog.csdn.net/wang704987562/article/details/81273899

4.回到之前的ioc原型

案例1的ioc原型,现在我们通过spring容器管理测试
那么我们引入applicationContext.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">
    <!-- 通过spring来创建对象,在spring称为bean
         id等价于原来new对象的句柄
     -->
    <!-- 注入dao层的实现类对象-->
    <bean id="daoMysql" class="com.wh.dao.impl.UserDaoMysqlImpl"/>
    <bean id="daoOracle" class="com.wh.dao.impl.UserDaoOracleImpl"/>

    <bean id="userService" class="com.wh.service.impl.UserServiceImpl">
        <!-- 引用spring容器创建好的对象,只需要修改这里即可 -->
        <property name="userDao" ref="daoMysql"/>
    </bean>
    
</beans>

重新测试下
在这里插入图片描述
想要修改dao层,只需要切换即可
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值