欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于xml文件的IOC配置

程序员文章站 2022-06-22 08:17:42
基于xml文件的IOC配置 简述 IOC的作用是降低程序间的耦合(依赖关系)而依赖关系的维护是由spring来维护的;我们在当前类使用到其他类的对象,这时spring提供这种关系的管理,我们只需要在配置文件中加以声明即可。我们称依赖关系的维护是依赖注入。 注入的数据 基本数据类型和String类型 ......

基于xml文件的ioc配置

  • 简述

    • ioc的作用是降低程序间的耦合(依赖关系)而依赖关系的维护是由spring来维护的;我们在当前类使用到其他类的对象,这时spring提供这种关系的管理,我们只需要在配置文件中加以声明即可。我们称依赖关系的维护是依赖注入。

  • 注入的数据

    • 基本数据类型和string类型

    • 其他bean类型

    • 复杂类型/集合类型

  • 注入方式

    • 使用构造函数提供

      • 使用constructor-arg标签,隶属于bean标签

      • 此标签属性的声明

        • type:用于要指定的数据的数据类型,这数据类型也是构造函数中某个或者某些参数的类型

        • index:用于要指定注入的参数在构造函数中指定参数的位置,从0开始

        • name:用于要制定的构造函数的参数名称 (强烈建议使用)

        • value:用于指定基本数据类型和string类型的数据

        • ref:用于指定基本数据类型和string类型的数据

          package com.mypro.service.impl;
          ​
          import com.mypro.dao.userdao;
          import com.mypro.dao.impl.userdaoimpl;
          import com.mypro.service.userservice;
          ​
          import java.util.date;
          ​
          /**
           * 用户的业务实现类
           */
          public class userserviceimpl implements userservice {
          ​
              // 经常变化的数据并不适用数据依赖注入
              private string name;
              private integer age;
              private date birth;
          ​
              public userserviceimpl(string name, integer age, date birth) {
                  this.name = name;
                  this.age = age;
                  this.birth = birth;
              }
          ​
              private userdao userdao = new userdaoimpl();
          ​
              @override
              public void saveuser() {
                  userdao.saveuser();
              }
          }
          ​

           

          <?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="now" class="java.util.date"></bean>
              <bean id="userservice" class="com.mypro.service.impl.userserviceimpl">
                  <constructor-arg name="name" value="xiansen"></constructor-arg>
                  <constructor-arg name="age" value="20"></constructor-arg>
                  <constructor-arg name="birth" value="now"></constructor-arg>
              </bean>
              <bean id="userdao" class="com.mypro.dao.impl.userdaoimpl">
              </bean>
          ​
          ​
          </beans>

           

    • 使用set方法提供

      • 使用property标签,隶属于bean标签

      • 此标签属性的声明

        • name:用于要制定的构造函数的参数名称 (强烈建议使用)

        • value:用于指定基本数据类型和string类型的数据

        • ref:用于指定基本数据类型和string类型的数据

          package com.mypro.dao.impl;
          ​
          import com.mypro.dao.userdao;
          ​
          import java.util.*;
          ​
          /**
           * 用户的持久层实现类
           */
          public class userdaoimpl implements userdao {
              // 经常变化的数据并不适用依赖注入
              private string name;
              private integer age;
              private date birth;
              // 复杂类型的数据的注入
              private string[] mystrs;
              private list<string> mylists;
              private set<string> mysets;
              private map<string, string> mymaps;
              private properties myprops;
          ​
              public void setmystrs(string[] mystrs) {
                  this.mystrs = mystrs;
              }
          ​
              public void setmylists(list<string> mylists) {
                  this.mylists = mylists;
              }
          ​
              public void setmysets(set<string> mysets) {
                  this.mysets = mysets;
              }
          ​
              public void setmymaps(map<string, string> mymaps) {
                  this.mymaps = mymaps;
              }
          ​
              public void setmyprops(properties myprops) {
                  this.myprops = myprops;
              }
          ​
              public void setname(string name) {
                  this.name = name;
              }
          ​
              public void setage(integer age) {
                  this.age = age;
              }
          ​
              public void setbirth(date birth) {
                  this.birth = birth;
              }
          ​
              @override
              public void saveuser() {
                  system.out.println("用户保存成功!");
              }
          }
           
          <?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="now" class="java.util.date"></bean>
              <bean id="userservice" class="com.mypro.service.impl.userserviceimpl">
                  <constructor-arg name="name" value="xiansen"></constructor-arg>
                  <constructor-arg name="age" value="20"></constructor-arg>
                  <constructor-arg name="birth" value="now"></constructor-arg>
              </bean>
              <!-- 复杂类型注入
                  用于list集合注入的标签
                      list、array、set
                  用于map集合注入的标签
                      map、props
                  结构相同的标签可以互换
               -->
              <bean id="userdao" class="com.mypro.dao.impl.userdaoimpl">
                  <property name="name" value="xiaohu"></property>
                  <property name="age" value="18"></property>
                  <property name="birth" ref="now"></property>
                  <property name="mystrs">
                      <array>
                          <value>aa</value>
                          <value>bb</value>
                      </array>
                  </property>
                  <property name="mylists">
                      <list>
                          <value>aa</value>
                          <value>bb</value>
                      </list>
                  </property>
                  <property name="mysets">
                      <set>
                          <value>aa</value>
                          <value>bb</value>
                      </set>
                  </property>
                  <property name="mymaps">
                      <map>
                          <entry key="aa" value="aa"></entry>
                          <entry key="bb">
                              <value>bb</value>
                          </entry>
                      </map>
                  </property>
                  <property name="myprops">
                      <props>
                          <prop key="aa">aa</prop>
                          <prop key="bb">bb</prop>
                      </props>
                  </property>
              </bean>
          ​
          ​
          </beans>

           

基于xml文件完成ioc配置(案例)

  • 使用dbutils包完成简单业务,导入必要的包

    <dependencies>
        <dependency>
          <groupid>org.springframework</groupid>
          <artifactid>spring-context</artifactid>
          <version>5.0.2.release</version>
        </dependency>
        <dependency>
          <groupid>commons-dbutils</groupid>
          <artifactid>commons-dbutils</artifactid>
          <version>1.4</version>
        </dependency>
        <dependency>
          <groupid>mysql</groupid>
          <artifactid>mysql-connector-java</artifactid>
          <version>5.1.6</version>
        </dependency>
        <dependency>
          <groupid>c3p0</groupid>
          <artifactid>c3p0</artifactid>
          <version>0.9.1.2</version>
        </dependency>
        <dependency>
          <groupid>junit</groupid>
          <artifactid>junit</artifactid>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>
    </dependencies>

     

  • 实体类words

    package com.mypro.entity;
    ​
    import java.util.date;
    ​
    public class words {
        private integer id;
        private string word;
        private string translation;
        private string introduction;
        private integer star;
        private date add_time;
        private integer group_id;
    ​
        @override
        public string tostring() {
            return "words{" +
                    "id=" + id +
                    ", word='" + word + '\'' +
                    ", translation='" + translation + '\'' +
                    ", introduction='" + introduction + '\'' +
                    ", star=" + star +
                    ", add_time=" + add_time +
                    ", group_id=" + group_id +
                    '}';
        }
    ​
        public integer getid() {
            return id;
        }
    ​
        public void setid(integer id) {
            this.id = id;
        }
    ​
        public string getword() {
            return word;
        }
    ​
        public void setword(string word) {
            this.word = word;
        }
    ​
        public string gettranslation() {
            return translation;
        }
    ​
        public void settranslation(string translation) {
            this.translation = translation;
        }
    ​
        public string getintroduction() {
            return introduction;
        }
    ​
        public void setintroduction(string introduction) {
            this.introduction = introduction;
        }
    ​
        public integer getstar() {
            return star;
        }
    ​
        public void setstar(integer star) {
            this.star = star;
        }
    ​
        public date getadd_time() {
            return add_time;
        }
    ​
        public void setadd_time(date add_time) {
            this.add_time = add_time;
        }
    ​
        public integer getgroup_id() {
            return group_id;
        }
    ​
        public void setgroup_id(integer group_id) {
            this.group_id = group_id;
        }
    }
  • 业务层接口wordsservice和实现类wordsserviceimpl (接口类省略)

    package com.mypro.entity;
    ​
    import java.util.date;
    ​
    public class words {
        private integer id;
        private string word;
        private string translation;
        private string introduction;
        private integer star;
        private date add_time;
        private integer group_id;
    ​
        @override
        public string tostring() {
            return "words{" +
                    "id=" + id +
                    ", word='" + word + '\'' +
                    ", translation='" + translation + '\'' +
                    ", introduction='" + introduction + '\'' +
                    ", star=" + star +
                    ", add_time=" + add_time +
                    ", group_id=" + group_id +
                    '}';
        }
    ​
        public integer getid() {
            return id;
        }
    ​
        public void setid(integer id) {
            this.id = id;
        }
    ​
        public string getword() {
            return word;
        }
    ​
        public void setword(string word) {
            this.word = word;
        }
    ​
        public string gettranslation() {
            return translation;
        }
    ​
        public void settranslation(string translation) {
            this.translation = translation;
        }
    ​
        public string getintroduction() {
            return introduction;
        }
    ​
        public void setintroduction(string introduction) {
            this.introduction = introduction;
        }
    ​
        public integer getstar() {
            return star;
        }
    ​
        public void setstar(integer star) {
            this.star = star;
        }
    ​
        public date getadd_time() {
            return add_time;
        }
    ​
        public void setadd_time(date add_time) {
            this.add_time = add_time;
        }
    ​
        public integer getgroup_id() {
            return group_id;
        }
    ​
        public void setgroup_id(integer group_id) {
            this.group_id = group_id;
        }
    }
  • 持久层接口wordsdao和实现类wordsdaoimpl(接口类省略)简单使用dbutils包

    package com.mypro.dao.impl;
    ​
    import com.mypro.dao.wordsdao;
    import com.mypro.entity.words;
    import org.apache.commons.dbutils.queryrunner;
    import org.apache.commons.dbutils.handlers.beanhandler;
    import org.apache.commons.dbutils.handlers.beanlisthandler;
    ​
    import java.util.list;
    ​
    public class wordsdaoimpl implements wordsdao {
        
        //为注入bean对象添加一个setter方法
        private queryrunner runner;
    ​
        public void setrunner(queryrunner runner) {
            this.runner = runner;
        }
    ​
        @override
        public list<words> findall() {
            try{
                return runner.query("select * from words", new beanlisthandler<words>(words.class));
            }catch(exception e){
                throw new runtimeexception(e);
            }
        }
    ​
        @override
        public words findwordsbyid(integer id) {
            try{
                return runner.query("select * from words where id=?", new beanhandler<words>(words.class), id);
            }catch (exception e){
                throw new runtimeexception(e);
            }
        }
    ​
        @override
        public void insertwords(words words) {
            try{
                runner.update("insert into words(word, translation, introduction, add_time, star, group_id)" +
                        "values(?,?,?,?,?,?)", words.getword(), words.gettranslation(), words.getintroduction(),
                        words.getadd_time(), words.getstar(), words.getgroup_id());
            }catch (exception e){
                throw new runtimeexception(e);
            }
        }
    ​
        @override
        public void updatewords(words words) {
            try{
                runner.update("update words set word=?, translation=?, introduction=?, add_time=?, star=?, group_id=? " +
                        "where id=?", words.getword(), words.gettranslation(), words.getintroduction(), words.getadd_time(),
                        words.getstar(), words.getgroup_id(), words.getid());
            }catch (exception e){
                throw new runtimeexception(e);
            }
        }
    ​
        @override
        public void deletewords(integer id) {
            try{
                runner.update("delete from words where id=?", id);
            }catch (exception e){
                throw new runtimeexception(e);
            }
        }
    }
  • bean对象容器mywordbean.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">
        <!-- 配置wordsservice对象 -->
        <bean id="wordsservice" class="com.mypro.service.impl.wordsserviceimpl">
            <!-- 注入wordsdao -->
            <property name="wordsdao" ref="wordsdao"></property>
        </bean>
        <!-- 配置wordsdao对象 -->
        <bean id="wordsdao" class="com.mypro.dao.impl.wordsdaoimpl">
            <!-- 注入runner -->
            <property name="runner" ref="runner"></property>
        </bean>
        <!-- 配置queryrunner对象 -->
        <bean id="runner" class="org.apache.commons.dbutils.queryrunner" scope="prototype">
            <!-- 注入数据源 -->
            <constructor-arg name="ds" ref="datasource"></constructor-arg>
        </bean>
        <!-- 配置数据源 -->
        <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource">
            <!-- 连接数据库 -->
            <property name="driverclass" value="com.mysql.jdbc.driver"></property>
            <property name="jdbcurl" value="jdbc:mysql://localhost:3306/myword"></property>
            <property name="user" value="username"></property>
            <property name="password" value="password"></property>
        </bean>
    </beans>

     

  • 测试类wordsservicetest

    package com.mypro.test;
    ​
    import com.mypro.entity.words;
    import com.mypro.service.wordsservice;
    import com.mypro.service.impl.wordsserviceimpl;
    import org.junit.before;
    import org.junit.test;
    import org.springframework.context.applicationcontext;
    import org.springframework.context.support.classpathxmlapplicationcontext;
    ​
    import java.util.date;
    import java.util.list;
    ​
    public class wordsservicetest {
        private wordsservice wordsservice;
        @before
        public void testinit(){
            applicationcontext ac = new classpathxmlapplicationcontext("mywordbean.xml");
            wordsservice = ac.getbean("wordsservice", wordsservice.class);
        }
    ​
        @test
        public void testfindall(){
            list<words> all = wordsservice.findall();
            for (words words : all) {
                system.out.println(words);
            }
        }
    ​
        @test
        public void testfindone(){
            integer id = 10;
            words words = wordsservice.findwordsbyid(id);
            system.out.println(words);
        }
    ​
        @test
        public void testinsert(){
            date now = new date();
            words words = new words();
            words.setword("java");
            words.settranslation("爪哇");
            words.setintroduction("一门编程语言");
            words.setadd_time(now);
            words.setstar(2);
            words.setgroup_id(1);
            wordsservice.insertwords(words);
            system.out.println("success insert!");
        }
    ​
        @test
        public void testupdate(){
            date now = new date();
            words words = new words();
            words.setid(9);
            words.setword("java web");
            words.settranslation("爪哇应用");
            words.setintroduction("一门编程语言");
            words.setadd_time(now);
            words.setstar(2);
            words.setgroup_id(1);
            wordsservice.updatewords(words);
            system.out.println("success update!");
        }
    ​
        @test
        public void testdelete(){
            integer id = 11;
            wordsservice.deletewords(id);
            system.out.println("success delete!");
        }
    }
    ​