Spring基础--基于XML配置的入门案例

1、创建Maven工程

IDEA2020记得选择quickstart
导入相关配置
pom.xml

<?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>org.example</groupId>
  <artifactId>day02_XmlIocCase</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>day02_XmlIocCase</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>
    <dependency>
      <groupId>commons-dbutils</groupId>
      <artifactId>commons-dbutils</artifactId>
      <version>1.7</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>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <!--添加配置跳过测试-->
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
          <configuration>
            <skipTests>true</skipTests>
          </configuration>
        </plugin>
        <!--添加配置跳过测试-->
      </plugins>
    </pluginManagement>
  </build>
</project>

2、创建实体类

创建domain包,同时创建Account.java


import java.io.Serializable;

/*
* 用户实体类
* */
public class Account implements Serializable {
    
    
    private Integer id;
    private String name;
    private float money;

    public Integer getId() {
    
    
        return id;
    }

    public void setId(Integer id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public float getMoney() {
    
    
        return money;
    }

    public void setMoney(float money) {
    
    
        this.money = money;
    }

    @Override
    public String toString() {
    
    
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

3、创建业务层接口和实现类

业务层接口:IAccountService.java

import org.example.domain.Account;

import java.util.List;

/*
* 业务层接口
* */
public interface AccountService {
    
    
    // 查询所有
    List<Account> findAll();

    // 根据id查询
    Account findById(Integer accountId);

    // 插入数据
    void insert(Account account);

    // 更新数据
    void update(Account account);

    // 根据Id删除数据
    void delete(Integer accountId);
}

业务层实现类:AccountServiceImpl.java

import org.example.dao.IAccountDao;
import org.example.domain.Account;
import org.example.service.AccountService;

import java.util.List;

/*
* 业务层接口的实现类
* */
public class IAccountServiceImpl implements AccountService {
    
    

    private IAccountDao accountDao;

    // 通过set方法来让spring自动注入accountDao
    public void setAccountDao(IAccountDao accountDao) {
    
    
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAll() {
    
    
        return accountDao.findAll();
    }

    @Override
    public Account findById(Integer accountId) {
    
    
        return accountDao.findById(accountId);
    }

    @Override
    public void insert(Account account) {
    
    
        accountDao.insert(account);
    }

    @Override
    public void update(Account account) {
    
    
        accountDao.update(account);
    }

    @Override
    public void delete(Integer accountId) {
    
    
        accountDao.delete(accountId);
    }
}

4、创建持久层接口和实现类

持久层接口: IAccountDao.java

import org.example.domain.Account;

import java.util.List;

/*
* 账户的持久层接口
* */
public interface IAccountDao {
    
    
    // 查询所有
    List<Account> findAll();

    // 根据id查询
    Account findById(Integer accountId);

    // 插入数据
    void insert(Account account);

    // 更新数据
    void update(Account account);

    // 根据Id删除数据
    void delete(Integer accountId);

}

持久层实现类: AccountDaoImpl.java

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.example.dao.IAccountDao;
import org.example.domain.Account;

import java.util.List;

/*
* 永久层实现类
* */
public class AccountDaoImpl implements IAccountDao {
    
    
    private QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
    
    
        this.queryRunner = queryRunner;
    }

    @Override
    public List<Account> findAll() {
    
    
        try{
    
    
            return queryRunner.query("select *from account", new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findById(Integer accountId) {
    
    
        try{
    
    
            return queryRunner.query("select *from account where id = ?", new BeanHandler<Account>(Account.class), accountId);
        }catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(Account account) {
    
    
        try{
    
    
            queryRunner.update("insert into account(name,money)values (?,?)", account.getName(),account.getMoney());
        }catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Account account) {
    
    
        try{
    
    
            queryRunner.update("update account set name = ?, money = ? where id = ?", account.getName(), account.getMoney(), account.getId());
        }catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(Integer accountId) {
    
    
        try{
    
    
            queryRunner.update("delete from account where id = ?", accountId);
        }catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }
}

5、配置文件

在resource文件夹中创建配置文件 Bean.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">
        <!-- 配置service -->
        <bean id="accountService" class="org.example.service.impl.IAccountServiceImpl">
            <!-- 注入dao -->
            <property name="accountDao" ref="accountDao"></property>
        </bean>

        <!-- 配置dao对象 -->
        <bean id="accountDao" class="org.example.dao.impl.AccountDaoImpl">
            <!-- 注入QueryRunner -->
            <property name="queryRunner" ref="queryRunner"></property>
        </bean>

        <!-- 配置queryRunner -->
        <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
            <!-- 注入数据源 -->
            <constructor-arg name="ds" ref="dataSource"></constructor-arg>
        </bean>

        <!-- 配置dataSource -->
        <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/spring"></property>
            <property name="user" value="root"></property>
            <property name="password" value="123456"></property>
        </bean>
</beans>

6、测试

@Test
    public void findAll() {
    
    
        // 1、获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        // 2、得到业务对象
        AccountService as = ac.getBean("accountService", AccountService.class);
        // 3、执行方法
        List<Account> accounts = as.findAll();
        for (Account account : accounts) {
    
    
            System.out.println(account);
        }
    }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44660367/article/details/108169869