通过一个银行转账的案例,手写实现IOC和AOP
通过上一篇面试被问了几百遍的 IoC 和 AOP,还在傻傻搞不清楚?我们了解了 IOC 和 AOP 这两个思想,下面我们先不去考虑Spring是如何实现这两个思想的,先通过一个银行转账的案例,分析一下该案例在代码层面存在什么问题?分析之后使用我们已有的知识来解决这些问题(痛点)。
其实这个过程就是在一步步分析并手动实现 IOC 和 AOP 。
案例介绍
银行转账:账户A向账户B转账(账户A减钱,账户B加钱)。为了简单起见,在前端页面中写死了两个账户。每次只需要输入转账金额,进行转账操作,验证功能即可。
案例表结构
name varcher 255 用户名money int 255 账户金额cardNo varcher 255 银行卡号
案例代码调用关系
核心代码
TransferServlet
@WebServlet(name='transferServlet',urlPatterns = '/transferServlet')public class TransferServlet extends HttpServlet {    // 1. 实例化service层对象    private TransferService transferService = new TransferServiceImpl();    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        doPost(req,resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        // 设置请求体的字符编码        req.setCharacterEncoding('UTF-8');        String fromCardNo = Parameter('fromCardNo');        String toCardNo = Parameter('toCardNo');        String moneyStr = Parameter('money');        int money = Integer.parseInt(moneyStr);        Result result = new Result();        try {            // 2. 调用service层方法            ansfer(fromCardNo,toCardNo,money);            result.setStatus('200');        } catch (Exception e) {            e.printStackTrace();            result.
setStatus('201');            result.String());        }        // 响应        resp.setContentType('application/json;charset=utf-8');        Writer().print(JsonUtils.object2Json(result));    }}
TransferService
TransferServiceImpl
AccountDao
JdbcAccountDaoImpl
public class JdbcAccountDaoImpl implements AccountDao { @Override public Account queryAccountByCardNo(String cardNo) throws Exception { //从连接池获取连接 Connection con = Instance().getConnection(); String sql = 'select * from account where cardNo=?'; PreparedStatement preparedStatement = con.prepareStatement(sql); prepared
Statement.setString(1,cardNo); ResultSet resultSet = uteQuery(); Account account = new Account(); ()) { account.String('cardNo')); account.String('name')); account.Int('money')); } resultSet.close(); preparedStatement.close(); con.close(); return account; } @Override public int updateAccountByCardNo(Account account) throws Exception { // 从连接池获取连接 Connection con = Instance().getConnection(); String sql = 'update account set money=? where cardNo=?'; PreparedStatement preparedStatement = con.prepareStatement(sql); preparedStatement.setInt(Money()); preparedStatement.setString(CardNo()); int i = uteUpdate(); preparedStatement.close(); con.close(); return i; }}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。