美文网首页
Spring--IOC

Spring--IOC

作者: 何以解君愁 | 来源:发表于2022-08-08 02:51 被阅读0次

IOC:反转控制(反转资源的获取方向,改由容器主动将资源推送给需要的组件,使用者不需要知道容器如何创建资源对象,只需要提供接收资源的方式即可)

DI:依赖注入,是IOC的一种具体实现(以预先定义好的方式对Spring管理的属性进行赋值)

ClassPathXmIApplicationContext:通过读取类路径下的XML格式的配置文件创建IOC容器对象
FileSystemXmlApplicationContext:通过文件系统路径读取XML格式的配置文件创建IOC容器对象
ConfigurableApplicationContext:ApplicationContext的子接口,包含一些扩展方法refresh()和close(),让ApplicationContext 具有启动、关闭和刷新上下文的能力
WebApplicationContext:专门为Web应用准备,基于Web环境创建IOC容器对象,并将对象引入存入ServletContext域中
使用:

<dependencies>
        <!--基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.1</version>
        </dependency>
        <!-- junit测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
</dependencies>
resources下的TestContext.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:配置一个bean对象,将对象交给IOC容器管理
        id:唯一标识,不能重复
        class:设置bean对象所对应的类型(包名加类名)
    -->
    <bean id="test" class="com.test"></bean>
</beans>

获取bean的三种方式:1、根据bean的id获取
2、根据bean的类型获取
注意:根据类型获取bean时,要求IOC容器中有且只有一个类型匹配的bean
若没有任何一个类型匹配的bean,此时抛出异常:NoSuchBeanDefinitionException若有多个类型匹配的bean,此时抛出异常:NoUniqueBeanDefinitionException
3、根据bean的id和类型获取

测试类:
public class tests {
    @Test
    public void test(){
        //获取IOC容器
        //resources和java最终会加载到同一路径下
        ApplicationContext ioc = new ClassPathXmlApplicationContext("TestContext.xml");
        //强转
        test test = (com.test) ioc.getBean("test");
        test.test();
    }
}

相关文章

网友评论

      本文标题:Spring--IOC

      本文链接:https://www.haomeiwen.com/subject/ipigwrtx.html