基于xml文件的IOC配置

2020-04-11 16:03:52来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

基于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<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;
        }
    }
    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<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);
            }
        }
    }
    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">
        <!-- 配置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!");
        }
    }
    ?

     


原文链接:https://www.cnblogs.com/aitiknowledge/p/12678271.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:基于注解的IOC配置

下一篇:JVM系列十(虚拟机性能监控神器 - BTrace).