Spring学习笔记(2)

IOC操作

  1. 什么是Bean管理

    Bean管理指的是两个操作:

    • Spring创建对象
    • Spring注入属性
  2. Bean管理操作有两种方式

    • 基于xml配置文件实现

    • 基于注解方式实现

      IOC操作Bean管理(基于xml方式)

      1. 基于xml方式创建对象

        在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建

            <!--
            bean标签:让spring创建一个对象并放置在IOC容器内
            属性:
                id : 标签该bean对象的唯一标识符,bean的名称,不能重复的
                class : 需要创建对象的类型的全限定名,spring通过反射机制创建该类的对象(要求:该类必须拥有无参构造方法)
            -->
            <bean id="user" class="com.lxk.User"></bean>
            <bean id="person" class="com.lxk.Person"></bean>
        
        
        • bean标签有很多属性,介绍常用的属性

          id属性:唯一标识

          class属性:类全路径(包类路径)

          (不常用)name:与id的区别为name可加特殊符号(struts1框架所用)

        • 创建对象时,默认也是执行无参数构造方法

      2. 基于xml方式注入属性

        • DI:依赖注入,就是注入属性(是IOC的一种实现)

          • 第一种注入方式:使用set方法进行注入
          <!--配置Book对象创建-->
              <bean id="book" class="com.lxk.Book">
                  <!--set方法注入属性-->
                  <!--使用property完成属性注入-->
                  <property name="bname" value="C++"></property>
              </bean>
          

          name:类里面属性名称

          value:向属性注入的值

          • 第二种注入方式:使用有参构造方法进行注入

            <!--使用有参构造方法进行注入-->
                <bean id="orders" class="com.lxk.Orders">
                    <constructor-arg name="oname" value="abc"></constructor-arg>
                    <constructor-arg name="address" value="China"></constructor-arg>
                </bean>
            
          • 第三种注入方式:p名称空间注入,可以简化基于xml配置方式

            第一步 添加p名称空间在配置文件中

            xmlns="http://www.springframework.org/schema/beans"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns:p="http://www.springframework.org/schema/p"
                    xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd">
                
            
            <!--使用p命名空间进行注入-->
                <bean id="orders" class="com.lxk.Orders" p:oname="abc" p:address="China"></bean>
            
            
      3. 字面量(属性初始值)

        • null值

          <property name="baddress">
              <!--NULL值-->
              <null/>
          </property>
          
        • 属性值包含特殊符号 例:<<中国>>

          也可以用转义符号

          <!--属性值包含特殊符号-->
          <property name="baddress">
              <value>
                  <![CDATA[<<中国>>]]>
              </value>
          </property>
          
      4. 注入属性-外部bean

        • 创建两个类service类和dao类

        • 在service调用dao里面的方法

        • 在Spring配置文件中进行配置

          <bean name="userService" class="com.lxk.service.UserService">
              <property name="userDao" ref="userDaoImpl"></property>
          </bean>
          <bean name="userDaoImpl" class="com.lxk.dao.impl.UserDaoImpl"></bean>
          

          ref属性:创建userDao对象bean标签id值

posted on 2022-04-20 21:14  18软工五班龙向昆  阅读(16)  评论(0编辑  收藏  举报

导航