Spring框架初次学习之IOC

对spring的理解:

spring就是一个容器,用来生成bean。spring的核心容器是benas。core。context(配置文件) ,expression。

IOC即:控制反转,

在没有IOC之前,直接new一个对象。会导致工作很麻烦。
由Spring创建对象实例——>IOC控制反转,创建实例由spring完成
IOC做法:从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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">

    <!--配置service
      <bean>需要配置的对象
      id:用于之后从spring容器中获得实例时使用的
      class:需要创建实例的全限定类名
    -->

    <bean id="userServiceId" class="com.xiewanru.IOC.UserServiceImpl"></bean>

在xml配置中,告诉spring容器,需要实例化的是哪个接口实现类,然后我们根据id取出bean。就能获得一个实例:

   public static void main(String[]args){
        String xmlPath="beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);

        //原来的办法
//        UserServices userServices = new UserServiceImpl();
//        userServices.addUser();

        //现在的
        UserServices userServices = (UserServices)applicationContext.getBean("userServiceId");
        userServices.addUser();

这样就能得到一个实例了。这只是最简单的,之后又不断的进化。IOC只是一种思想,对于spring框架来说,就是由spring来负责控制对象的生命周期和对象间的关系

总结:我会在之后的学习中不断深化对于spring的学习和对IOC的理解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值