【Spring】基于xml的ioc案例测试

文章目录

  • 1. pom.xml配置
  • 2. 数据库表格对应的类
    • 2.1 数据库表格信息
    • 2.2 类
  • 3. 数据库DAO类
  • 4. Service层代码
  • 5. xml配置文件的设置
  • 测试代码

1. pom.xml配置

dbutils、c3p0

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mj</groupId>
    <artifactId>day02_02xml_ioc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.6.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>8.0.19</version>
        </dependency>

<!--c3p0 开源的JDBC数据库连接池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>


        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  </project>

2. 数据库表格对应的类

2.1 数据库表格信息

【Spring】基于xml的ioc案例测试_第1张图片

2.2 类

package com.mj.domain;

import java.io.Serializable;
import java.util.Date;

public class User  implements Serializable{
    //变量名称与数据库表中字段一致
    private Integer id;
    private  String username;
    private Date birthday;
    private  String sex;
   /* 补充驼峰命名规则:若数据库中含字段名形式为:xx_xx,
      则在java中对应形式为xxXx(_后面字母大写)
      开启驼峰命名:在主配置文件中设置参数mapUnderscoreToCamelCase的值为true
    */

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", usename='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                '}';
    }
}

3. 数据库DAO类

基于dbutils的QueryRunner类创建一系列对数据库的操作方法

package com.mj.dao;
import com.mj.domain.User;
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 UserDaoImpl implements IUserDao{
    private  QueryRunner runner;

    public void setRunner(QueryRunner runner) {
       this.runner = runner;
    }

    @Override
    public List<User> findAll() {

        try {
            return runner.query("select * from user", new BeanListHandler<User>(User.class));
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }

    @Override
    public User getUserById(Integer id) {
        try {
            return runner.query("select * from user where id=?",new BeanHandler<User>(User.class),id);
        }catch (Exception e){
            throw  new RuntimeException(e);
        }

    }

    @Override
    public User getUserByIdandsex(Integer id, String sex) {
        try {
            return runner.query("select * from user where id=? and sex=?",new BeanHandler<User>(User.class),id,sex);
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }

    @Override
    public void updateUser(User user) {
        try {
            runner.update("update user set username=?,sex=? where id=?",user.getUsername(),user.getSex(),user.getId());
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    @Override
    public void insertUser(User user) {
        try {
            runner.update("Insert into user (username,birthday,sex) values (?,?,?)",user.getUsername(),user.getBirthday(),user.getSex());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void deleteUser(Integer id) {
        try {

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

4. Service层代码

package com.mj.service;

import com.mj.dao.IUserDao;
import com.mj.domain.User;

import java.util.List;

public class AccountService {
    IUserDao userDao;

    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }
    public List<User> findAll(){
        return userDao.findAll();
    }


    public User getUserById(Integer id){
     return   userDao.getUserById(id);
    };

    public  User getUserByIdandsex(Integer id, String sex){
      return  userDao.getUserByIdandsex(id,sex);
    };

    public void updateUser(User user){
        userDao.updateUser(user);
    };

    public  void insertUser(User user){
        userDao.insertUser(user);
    };

    public  void deleteUser(Integer id){
       userDao.deleteUser(id);

    };
}

5. 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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="accountService" class="com.mj.service.AccountService">
        <property name="userDao" ref="userDao"></property>
    </bean>

    <bean id="userDao" class="com.mj.dao.UserDaoImpl">
        <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>

<!--配置数据源
    set方法注入-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- AbstractComboPooledDataSource类中的set方法-->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mytest?serverTimezone=GMT"/>
        <property name="user" value="root"/>
        <property name="password" value="1234567890"/>
    </bean>

</beans>

测试代码

import com.mj.domain.User;
import com.mj.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Client {
    
@Test
public void testFindAll(){

//创建spring的ioc容器
    ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
    //获取Service对象
    AccountService as=ac.getBean("accountService",AccountService.class);
    //调用Bean对象的方法
    List<User> list=as.findAll();
    System.out.println(list);

}
@Test
public void testGetUserById(){
    ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
    AccountService as=ac.getBean("accountService",AccountService.class);
    User u=as.getUserById(2);
    System.out.println(u);
}
@Test
public void testGetUserByIdandSex(){
    ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
    AccountService as=ac.getBean("accountService",AccountService.class);
    User u=as.getUserByIdandsex(1,"女");
    System.out.println(u);
}
@Test
public void testUpdateUser(){
    ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
    AccountService as=ac.getBean("accountService",AccountService.class);
    User u=new User();
    u.setUsername("秋秋");
    u.setId(3);
    u.setSex("女");
    as.updateUser(u);
    System.out.println(as.getUserById(u.getId()));
}
    @Test
    public void testInsertUser(){
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        AccountService as=ac.getBean("accountService",AccountService.class);
        User u=new User();
        u.setUsername("绿绿");
        u.setSex("女");
        as.insertUser(u);
        System.out.println(as.findAll());
    }
}

你可能感兴趣的:(框架)