基于xml文件的IOC配置

基于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 myLists;
              private Set mySets;
              private Map myMaps;
              private Properties myProps;
          ​
              public void setMyStrs(String[] myStrs) {
                  this.myStrs = myStrs;
              }
          ​
              public void setMyLists(List myLists) {
                  this.myLists = myLists;
              }
          ​
              public void setMySets(Set mySets) {
                  this.mySets = mySets;
              }
          ​
              public void setMyMaps(Map 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>
              
              <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>AAvalue>
                          <value>BBvalue>
                      array>
                  property>
                  <property name="myLists">
                      <list>
                          <value>AAvalue>
                          <value>BBvalue>
                      list>
                  property>
                  <property name="mySets">
                      <set>
                          <value>AAvalue>
                          <value>BBvalue>
                      set>
                  property>
                  <property name="myMaps">
                      <map>
                          <entry key="aa" value="AA">entry>
                          <entry key="bb">
                              <value>BBvalue>
                          entry>
                      map>
                  property>
                  <property name="myProps">
                      <props>
                          <prop key="aa">AAprop>
                          <prop key="bb">BBprop>
                      props>
                  property>
              bean>
          ​
          ​
          beans>

           

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

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

    <dependencies>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-contextartifactId>
          <version>5.0.2.RELEASEversion>
        dependency>
        <dependency>
          <groupId>commons-dbutilsgroupId>
          <artifactId>commons-dbutilsartifactId>
          <version>1.4version>
        dependency>
        <dependency>
          <groupId>mysqlgroupId>
          <artifactId>mysql-connector-javaartifactId>
          <version>5.1.6version>
        dependency>
        <dependency>
          <groupId>c3p0groupId>
          <artifactId>c3p0artifactId>
          <version>0.9.1.2version>
        dependency>
        <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>4.11version>
          <scope>testscope>
        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;
        }
    }
    View Code
  • 业务层接口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 findAll() {
            try{
                return runner.query("select * from words", new BeanListHandler(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.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);
            }
        }
    }
    View Code
  • 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">
        
        <bean id="wordsService" class="com.mypro.service.impl.WordsServiceImpl">
            
            <property name="wordsDao" ref="wordsDao">property>
        bean>
        
        <bean id="wordsDao" class="com.mypro.dao.impl.WordsDaoImpl">
            
            <property name="runner" ref="runner">property>
        bean>
        
        <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 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!");
        }
    }
    ​

     

你可能感兴趣的:(基于xml文件的IOC配置)