Spring框架 - 开发方式

目录

项目目录

Spring框架开发方式


项目目录

复制代码
com/qcby/
├── dao/            --数据访问层(Data Access Object)
│   ├── impl/       --接口实现类
│   │   └── AccountDaoImpl.java     --AccountDao接口的实现
│   └── AccountDao.java             --账户数据访问接口
├── model/          --实体模型层
│   └── Account.java                --账户实体类
└── service/       --业务逻辑层
    ├── impl/      --接口实现类
    │   └── AccountServiceImpl.java --AccountService接口的实现
    └── AccountService.java         --账户业务逻辑接口

main/resources/ - 资源配置

  • applicationContext.xml - Spring 核心配置文件,用于 Bean 管理和依赖注入

test/java/com/qcby/ - 测试代码

  • AccountTest.java - 账户相关的测试类

Spring框架开发方式

1. 创建数据库,创建表结构

sql 复制代码
create database spring_db;
use spring_db;
create table account(
    id int primary key auto_increment,
    name varchar(40),
    money double
)character set utf8 collate utf8_general_ci;
​
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);

2. 导入依赖:pom.xml

  • 创建maven Java项目
  • 导入开发jar包
  • 持久层使用原始的JDBC程序,连接池使用Druid连接池。
XML 复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!-- 连接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.10</version>
    </dependency>
    <!-- mysql驱动包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
</dependencies>

3. 编写JavaBean的类: Account类

  • 实现Serializable接口
  • 设置私有属性:id、name、money
  • 设置公共getter/setter
  • 重新toString()方法
java 复制代码
package com.qcby.model;

import java.io.Serializable;

public class Account implements Serializable {
    private static final long serialVersionUID = 7355810572012650248L;
    private Integer id;
    private String name;
    private Double 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 Double getMoney() {
        return money;
    }

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

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

4. 编写数据访问层的接口: AccountDao类

java 复制代码
package com.qcby.dao;

import com.qcby.model.Account;

import java.util.List;

public interface AccountDao {
    public List<Account> findAll();
}

5. 编写AccountDao的实现类: AccountDaoImpl类

  • 注入连接池对象:通过**setter方法(DI依赖注入)**注入DataSource
java 复制代码
// 注入连接池对象
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}
  • 实现findAll()方法

    • 初始化
    java 复制代码
    List<Account> list = new ArrayList<>();
    Connection connection = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    • 从连接池中获取数据库连接
    java 复制代码
    // 获取连接
    connection = dataSource.getConnection();
    • 执行SQL
      • 使用PreparedStatement防止SQL注入
      • 执行查询获取结果集
    java 复制代码
    // 编写sql语句
    String sql = "select * from account";
    // 预编译
    stmt = connection.prepareStatement(sql);
    // 查询
    rs = stmt.executeQuery();
    • 结果集处理
    java 复制代码
    // 遍历,封装数据
    while (rs.next()){
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getDouble("money"));
        list.add(account);
    }
    • 关闭资源
    java 复制代码
    finally {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

完整代码:

java 复制代码
package com.qcby.dao.impl;

import com.qcby.dao.AccountDao;
import com.qcby.model.Account;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AccountDaoImpl implements AccountDao {
     // 注入连接池对象
     private DataSource dataSource;
     public void setDataSource(DataSource dataSource) {
         this.dataSource = dataSource;
     }

     /**
    * 查询所有的数据
    * @return
    */

     @Override
     public List<Account> findAll() {
         /*
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql:///spring_db");
            dataSource.setUsername("root");
            dataSource.setPassword("root");
        */
         List<Account> list = new ArrayList<>();
         Connection connection = null;
         PreparedStatement stmt = null;
         ResultSet rs = null;

         try {
             // 获取连接
            connection = dataSource.getConnection();
            // 编写sql语句
            String sql = "select * from account";
            // 预编译
            stmt = connection.prepareStatement(sql);
            // 查询
            rs = stmt.executeQuery();
            // 遍历,封装数据
            while (rs.next()){
                Account account = new Account();
                account.setId(rs.getInt("id"));
                account.setName(rs.getString("name"));
                account.setMoney(rs.getDouble("money"));
                list.add(account);
            }
         } catch (SQLException e) {
             e.printStackTrace();
         }finally {
             try {
                 connection.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
             try {
                 stmt.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
             try {
                 rs.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }
         return list;
     }
}

6. 编写业务层的接口: AccountService类

java 复制代码
package com.qcby.service;

import com.qcby.model.Account;

import java.util.List;

public interface AccountService {
    public List<Account> findAll();
}

7. 编写AccountService的实现类: AccountServiceImpl类

  • 注入依赖:通过setter方法(DI依赖注入),通过AccountDao访问数据层
  • 查询数据
java 复制代码
package com.qcby.service.impl;

import com.qcby.dao.AccountDao;
import com.qcby.model.Account;
import com.qcby.service.AccountService;

import java.util.List;

public class AccountServiceImpl implements AccountService {
    // 依赖注入
     private AccountDao accountDao;
     public void setAccountDao(AccountDao accountDao) {
         this.accountDao = accountDao;
     }
     /**
     * 查询所有的数据
     * @return
     */
     @Override
     public List<Account> findAll() {
         return accountDao.findAll();
     }
}

8. 编写配置文件: applicationContext.xml

  • 使用Bean配置连接池
  • 使用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">

    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///spring_db"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    <!--管理bean-->
    <bean id="accountService" class="com.qcby.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao" />
    </bean>
    <bean id="accountDao" class="com.qcby.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

9. 编写测试类: AccountTest类

java 复制代码
package com.qcby;

import com.qcby.model.Account;
import com.qcby.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class AccountTest {
    @Test
    public void run1(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = (AccountService) ac.getBean("accountService");
        // 调用方法
        List<Account> list = accountService.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
    }
}
相关推荐
無限進步D2 小时前
Java 运行原理
java·开发语言·入门
難釋懷2 小时前
安装Canal
java
是苏浙2 小时前
JDK17新增特性
java·开发语言
不光头强2 小时前
spring cloud知识总结
后端·spring·spring cloud
GetcharZp5 小时前
告别 Python 依赖!用 LangChainGo 打造高性能大模型应用,Go 程序员必看!
后端
阿里加多5 小时前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
likerhood5 小时前
java中`==`和`.equals()`区别
java·开发语言·python
小小李程序员5 小时前
Langchain4j工具调用获取不到ThreadLocal
java·后端·ai