设为首页 加入收藏

TOP

Spring IOC容器的基本应用
2018-03-18 16:21:37 】 浏览:87
Tags:Spring IOC 容器 基本 应用

Spring IOC概述


  IOC全称Inversion of Control,被译为控制反转,是指程序中对象的获取方式发生反转,由最初的new方式创建,转变为由第三方框架创建、注入(DI),它降低了对象之间的耦合度。


  Spring容器是IOC机制的一种实现,同时IOC也是Spring框架的基础和核心,它借助DI(Dependency Injection)方法实现。


Spring Bean容器


   Spring容器是Spring框架中的核心组件,负责创建Bean对象(一种简单规范的JAVA对象)及管理这些对象之间的依赖关系。


  Spring容器是如何工作的呢?在Spring项目运行是,Spring容器负责读取项目中的元数据信息(这些元数据可能是基于xml、也可能是基于注解实现),然后这些信息创建Bean对象的实例。


  IOC是Spring框架中的一种机制,提供了容器中对象的控制反转功能,这个功能的实现需要借助依赖查找和依赖注入。


Spring容器元数据配置


  Spring中元数据的配置有两种方式,基于xml或annotation方式。这个小节了解基于XML方式的元数据实现bean元素的基本配置(后续在描述annotation方式)。


<?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 id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>


    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>


    <!-- more bean definitions go here -->


</beans>


Spring中多个元素配置文件的实现方法


<beans>
    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="/resources/themeSource.xml"/>


    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>
</beans>


Spring容器的初始化


  Spring中容器的类型为Application类型,其初始化方法如下:


ApplicationContext context =


new ClassPathXmlApplicationContext("beans.xml");


  Spring容器初始化是需要加载元数据的配置信息,类如beans.xml文件中声明的元数据的相关配置。


Spring 容器的使用


  Spring容器初始化以后,可以通过容器的getBean(...)方法获取容器的Bean对象,进而操作Bean对象,例如:


Contex.getBean(“xxxService”,XxxService.class);


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java浮点数转人民币读法 下一篇SpringMVC国际化支持实现

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目