Spring IoC / DI 实现步骤

Spring IoC / DI 实现步骤

  1. 配置元数据(配置)

    配置元数据,既是编写交给SpringIoC容器管理组件的信息,配置方式有三种。

    基于 XML 的配置元数据的基本结构:

    <bean id=“…” [1] class=“…” [2]>
    <!-- collaborators and configuration for this bean go here -->
    </bean>

    <?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="..." [1] class="..." [2]>  
        <!-- 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 IoC 容器管理一个或多个组件。这些 组件是使用你提供给容器的配置元数据(例如,以 XML <bean/> 定义的形式)创建的。

    <bean /> 标签 == 组件信息声明

    • id 属性是标识单个 Bean 定义的字符串。
    • class 属性定义 Bean 的类型并使用完全限定的类名。
  2. 实例化IoC容器

    提供给 ApplicationContext 构造函数的位置路径是资源字符串地址,允许容器从各种外部资源(如本地文件系统、Java CLASSPATH 等)加载配置元数据。

    我们应该选择一个合适的容器实现类,进行IoC容器的实例化工作:

    //实例化ioc容器,读取外部配置文件,最终会在容器内进行ioc和di动作
    ApplicationContext context = 
               new ClassPathXmlApplicationContext("services.xml", "daos.xml");
    
  3. 获取Bean(组件)

    ApplicationContext 是一个高级工厂的接口,能够维护不同 bean 及其依赖项的注册表。通过使用方法 T getBean(String name, Class<T> requiredType) ,您可以检索 bean 的实例。

    允许读取 Bean 定义并访问它们,如以下示例所示:

    //创建ioc容器对象,指定配置文件,ioc也开始实例组件对象
    ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
    //获取ioc容器的组件对象
    PetStoreService service = context.getBean("petStore", PetStoreService.class);
    //使用组件对象
    List<String> userList = service.getUsernameList();
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值