Spring-ioc

Spring-ioc

在Spring-core模块中,包括了控制反转(IOC)与依赖注入(DI)两个功能,那么什么是控制反转呢?

IOC思想

​ 举个例子,例如今晚晚上加班了,太累了,实在干不动了,怎么办呢,对,吃,所以你就走进了你的厨房,拿起你的锅,一顿操作后,泡面煮好了,没错,红烧的。这像不像你在java中,new一个对象,是吧,你想吃,就new一个嘛,new个红烧牛肉面。这时,是不是你是整个事件的控制人,你想吃什么,就new什么,你高兴就好。但是呢,你觉得太累了,为什么我要吃,就一定要自己做呢?

​ 于是乎,各种商家出现了,好多夜宵店,你只需要知道你想吃什么,打开微信,点外卖就可以了,就马上就有东西吃了。那你这个时候还new吗?毛线,肯定不了,商家给我做好了呀,对吧,你就会发现,主动权变了,之前是我自己做,现在变成商家做我想吃的。对比过来,我不用做啦,在java中,是不是我就不用new了,是的,不用了,这个活有人帮你干了,谁干的。Spring微微一笑,你用的什么框架,啊对对对,Spring帮我们干了。这就是控制反转的思想。仔细一思考,为什么需要这个,对,降低耦合。那怎么实现呢?IOC容器来实现,实现的方法是什么,依赖注入。

IOC容器

Spring IOC容器的设计主要是基于BeanFactory和ApplicationContext两个接口。

BeanFactory

​ BeanFactory是在org.springframework.beans.factory.BeanFactory接口定义,是一个管理Bean的工厂,主要负责初始化Bean。其中XmlBeanFactory实现了该接口,下面通过一个具体的例子来演示一下。

我是在以前的工程里面创建的子工程,具体的可以参考以前的代码。这是我的目录结构

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Zwcevxm2-1665059112245)(C:/Users/wsy/AppData/Roaming/Typora/typora-user-images/image-20221003212155867.png)]

IocTestMapper.java

package com.wang.mapper;

public interface IocTestMapper {
    public void iocTest();
}

IocTestMapperImpl.java

package com.wang.mapper;

public class IocTestMapperImpl implements IocTestMapper {
    public void iocTest() {
        System.out.println("IOC得到了");
    }
}

TestApp.java

package com.wang.mapper;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class TestApp {
    public static void main(String[] args) {
        BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("D:\\idea项目\\spring-study\\spring-study-ioc\\src\\main\\resources\\applicationcontext.xml"));
        IocTestMapper iocTest = (IocTestMapperImpl)beanFactory.getBean("iocTest");
        iocTest.iocTest();
    }
}

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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="iocTest" class="com.wang.mapper.IocTestMapperImpl"/>

</beans>
  • 值得注意的是,XmlBeanFactory这个类已经被舍弃掉了,故只需要了解即可,在这里,xml文件的路径要填全路径

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LacPBCVF-1665059112247)(C:/Users/wsy/AppData/Roaming/Typora/typora-user-images/image-20221003214039525.png)]

ApplicationContext

在我的学习中,用ApplicationContext接口还是比较多的,它是BeanFactory的子接口,也就意味着它有BeanFactory的所有方法。ApplicationContext也成为应用上下文,除了父的方法外,还额外有别的方法,例如国际化,后续会加紧学习。

同样,我也通过几个例子来演示一下。还是用之前的工程,这里只需要把测试类变一下就可以了。

ClassPathXmlApplicationContext

创建ApplicationContext接口实例的方法一,通过ClassPathXmlApplicationContext创建
TestClassPathXmlApp.java

package com.wang.mapper;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestClassPathXmlApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
        IocTestMapper test = (IocTestMapperImpl)context.getBean("iocTest");
        test.iocTest();
        System.out.println("ClassPathXmlApplicationContext获得的");
    }
}

运行结果为
在这里插入图片描述

FileSystemXmlApplicationContext

创建ApplicationContext接口实例的方法一,通过FileSystemXmlApplicationContext创建
在这里插入图片描述

FiileSystemXmlApp.java

package com.wang;

import com.wang.mapper.IocTestMapper;
import com.wang.mapper.IocTestMapperImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class FiileSystemXmlApp {
    public static void main(String[] args) {
        ApplicationContext context = new FileSystemXmlApplicationContext("D:\\idea项目\\spring-study\\spring-study-ioc\\src\\main\\resources\\applicationcontext.xml");
        IocTestMapper iocTest = (IocTestMapperImpl)context.getBean("iocTest");
        System.out.println("FileSystemXml得到的");
        iocTest.iocTest();
    }
}

运行结果
在这里333

依赖注入

​ 前面提到,实现IOC容器的方法是依赖注入,那么什么是依赖注入呢,我的理解是Spring不是已经帮我们动态的创建对象了嘛。但是呢,有个问题是创建的对象没有装配呀,也许我用实例化表达有错,就是这个对象的属性没有初始值或者没有想要的值,而我们使用依赖注入,就可以动态的把这个对象所依赖的对象(注意,可能是属性值,也可能是对象呀,思想不要局限)自动的注入到Bean中,也就是说,通过这个依赖注入,在Spring容器中的一个一个Bean组件,装配了,就有确切的值了。

​ 依赖注入通常有两种方式,一种是构造方法注入,一种是使用属性的setter方法注入。

构造器注入

构造器注入,很常见,我也测试了几种,反正我个人觉得最好用的就是直接用name,用下标的形式也可以,但是用类型对应的方式,局限性就太大了,只能在简单的场景中使用,这里三个我都尝试了一下,话不多说,直接上代码

<?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="iocTest" class="com.wang.mapper.IocTestMapperImpl"/>
    <bean id="user" class="com.wang.pojo.User">
        <constructor-arg index="0" value="cxzwxz"/>
        <constructor-arg index="1" value="22"/>
    </bean>
    <bean id="Uservice" class="com.wang.service.Uerservice">
        <constructor-arg index="0" ref="user"/>
        <constructor-arg index="1" value="181856"/>
    </bean>
    <bean id="Uservices" class="com.wang.service.Uerservice">
        <constructor-arg name="user" ref="user"/>
        <constructor-arg name="tel" value="181856"/>
    </bean>
    <bean id="Uservicess" class="com.wang.service.Uerservice">
        <constructor-arg type="com.wang.pojo.User" ref="user"/>
        <constructor-arg type="int" value="181856"/>
    </bean>

</beans>

大致讲解一下,我用了一个User类做测试,id就是这个bean的唯一名字吧,调用的时候就用这个id,index就是构造器的下标,是按照参数前后顺序排序的,至于有个ref与value,ref是代表引用一个bean,而value就是直接给一个变量赋值。

User.java

package com.wang.pojo;
public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Uerservice.java

package com.wang.service;
import com.wang.pojo.User;
public class Uerservice {
    private User user;
    private int tel;
    public Uerservice(User user, int tel) {
        this.user = user;
        this.tel = tel;
    }
    public Uerservice(){

    }
    public int getTel() {
        return tel;
    }
    public User getUser(){
        return user;
    }

}

项目目录
在这里插入图片描述

测试代码

TestClassPathXmlApp.java

package com.wang;
import com.wang.pojo.User;
import com.wang.service.Uerservice;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestClassPathXmlApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
        Uerservice test = (Uerservice)context.getBean("Uservice");
        Uerservice tests = (Uerservice)context.getBean("Uservices");
        Uerservice testss = (Uerservice)context.getBean("Uservicess");
        int tel = test.getTel();
        User user = test.getUser();
        int tels = test.getTel();
        User users = test.getUser();
        int telss = test.getTel();
        User userss = test.getUser();
        System.out.println(tel);
        System.out.println(user.toString());
        System.out.println(tels);
        System.out.println(users.toString());
        System.out.println(telss);
        System.out.println(userss.toString());
    }
}

  • 值得注意的是,构造器注入,必须得有有参构造函数
setter方法注入

至于setter方式注入,其实和构造器差不多,只是标签换了个名字而已

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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="iocTest" class="com.wang.mapper.IocTestMapperImpl"/>
    <bean id="user" class="com.wang.pojo.User">
        <constructor-arg index="0" value="cxzwxz"/>
        <constructor-arg index="1" value="22"/>
    </bean>
    <bean id="Uservice" class="com.wang.service.Uerservice">
        <constructor-arg index="0" ref="user"/>
        <constructor-arg index="1" value="181856"/>
    </bean>
    <bean id="Uservices" class="com.wang.service.Uerservice">
        <constructor-arg name="user" ref="user"/>
        <constructor-arg name="tel" value="181856"/>
    </bean>
    <bean id="Uservicess" class="com.wang.service.Uerservice">
        <constructor-arg type="com.wang.pojo.User" ref="user"/>
        <constructor-arg type="int" value="181856"/>
    </bean>
    <bean id="serUserService" class="com.wang.service.Uerservice">
        <property name="tel" value="222"/>
        <property name="user" ref="user"/>
    </bean>

</beans>

Uerservice.java

package com.wang.service;
import com.wang.pojo.User;
public class Uerservice {
    private User user;
    private int tel;
    public Uerservice(User user, int tel) {
        this.user = user;
        this.tel = tel;
    }
    public Uerservice(){

    }
    public int getTel() {
        return tel;
    }
    public User getUser(){
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void setTel(int tel) {
        this.tel = tel;
    }
}

在这里,添加了set方法,这是为了以后的setter注入

测试类的话可以参考之前的构造器的测试,都是一样的逻辑,利用接口读取xml文件,从文件中获取bean的配置,然后调用方法,这里就不展示了。

package com.wang;
import com.wang.pojo.User;
import com.wang.service.Uerservice;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestClassPathXmlApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
        Uerservice test = (Uerservice)context.getBean("Uservice");
        Uerservice tests = (Uerservice)context.getBean("Uservices");
        Uerservice testss = (Uerservice)context.getBean("Uservicess");
        Uerservice serUserService = (Uerservice)context.getBean("serUserService");
        int tel = test.getTel();
        User user = test.getUser();
        int tels = test.getTel();
        User users = test.getUser();
        int telss = test.getTel();
        User userss = test.getUser();
//        System.out.println(tel);
//        System.out.println(user.toString());
//        System.out.println(tels);
//        System.out.println(users.toString());
//        System.out.println(telss);
//        System.out.println(userss.toString());
        int tel1 = serUserService.getTel();
        User user1 = serUserService.getUser();
        System.out.println("tel:"+tel+"   user"+user1.toString());
    }
}

在这里插入图片描述
还是贴上吧哈哈哈哈哈。

好啦,IOC就到这里啦。

总结一下就是Spring的IOC控制反转的思想,其实现的方式的依赖注入,依赖注入常见的两种方式是构造器注入以及setter注入。

在注意一下ref以及value就可以啦

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值