【手写框架】2. Spring IOC 和 AOP

手写spring的IOC 和 AOP框架

我们都知道spring 框架的核心就是IOC 和AOP,但是直接翻阅源码对于刚开始用spring的小伙伴会有些难度,所以这里我们实现一个简单的手写IOC 和 AOP来帮助小伙伴们更好的理解spring的底层实现。
我们使用一个模拟用户转账的场景来实现IOC 和 AOP
我们先来看下项目的整理调用流程图
在这里插入图片描述
我们对这张图来进行一下简单的分析

  • beans.xml 配置我们的bean对象
  • Beanfactory 用来解析beans.xml中需要我们管理的对象,如果有依赖关系通过set方法进行注入。最后存储到一个hashMap中,供调用
  • DruidsUtils 获取druid数据源
  • ConnectionUtils 获取数据库链接,引入ThreadLocal,保证一个线程只有一个数据库连接
  • TransactionManager 管理事务
  • ProxyFactory 用来创建代理对象

准备工作

  • 创建数据 spring
  • 创建表 account
  • 添加至少2条数据

创建maven项目

在这里插入图片描述

项目命名为spring-ioc

在这里插入图片描述

项目结构

在这里插入图片描述

引入项目依赖的jar包

<?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>spring-ioc</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.26</version>
        </dependency>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>

创建account实体类

@Data
@ToString
public class Account {

    private String cardId;

    private String accountName;

    private Integer money;
}

创建数据库连接池Druid工具类

public class DruidsUtils {

    private DruidsUtils() {
    }

    private static final DruidsUtils instance = new DruidsUtils();

    public static DruidsUtils getInstance() {
        return instance;
    }

    public Connection getConnection() {
        Connection connection = null;
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");
        try {
            connection = druidDataSource.getConnection();
        } catch (SQLException e) {
            System.out.println("获取数据库连接异常");
            e.printStackTrace();
        }
        return connection;
    }
}

创建数据库连接工具类

public class ConnectionUtils {

    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

    public Connection getCurrentThreadConn() {
        Connection connection = threadLocal.get();
        if (connection == null) {
            connection = DruidsUtils.getInstance().getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }
}

接下来我们创建数据库接口层以及实现类

AccountDao接口

public interface AccountDao {

    /**
     * 通过card id获取账户信息
     * @param cardId card id
     * @return 账户信息
     */
    Account getAccountByCartId(String cardId);

    /**
     * 修改账户金额
     * @param account Account
     */
    void updateAccount(Account account);
}

AccountDaoImpl实现类

public class AccountDaoImpl implements AccountDao {

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    @Override
    public Account getAccountByCartId(String cardId) {
        String sql = "select * from account where card_id = ?";
        try {
            Connection connection = connectionUtils.getCurrentThreadConn();
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, cardId);

            ResultSet resultSet = preparedStatement.executeQuery();
            Account account = new Account();
            while (resultSet.next()) {
                account.setCardId(resultSet.getString("card_id"));
                account.setAccountName(resultSet.getString("account_name"));
                account.setMoney(resultSet.getInt("money"));
            }
            return account;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void updateAccount(Account account) {
        String sql = "update account set money = ? where card_id = ?";
        try {
            Connection connection = connectionUtils.getCurrentThreadConn();
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, account.getMoney());
            preparedStatement.setString(2, account.getCardId());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

服务层接口以及实现类

AccountService接口

public interface AccountService {

    /**
     * 转账
     * @param transferFrom 转账人账户
     * @param transferTo 收款人账户
     * @param money 转账金额
     */
    void transferMoney(String transferFrom, String transferTo, Integer money);
}

AccountServiceImpl实现类

public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transferMoney(String transferFrom, String transferTo, Integer money) {
        Account fromAccount = accountDao.getAccountByCartId(transferFrom);
        Account toAccount = accountDao.getAccountByCartId(transferTo);
        fromAccount.setMoney(fromAccount.getMoney() - money);
        accountDao.updateAccount(fromAccount);
        toAccount.setMoney(toAccount.getMoney() + money);
        accountDao.updateAccount(toAccount);
    }
}

创建beans.xml 来配置我们需要管理的bean对象

<?xml version="1.0" encoding="UTF-8" ?>
<beans>
    <!--链接工具类-->
    <bean id="connectionUtils" class="com.spring.utils.ConnectionUtils"/>
    <!--事务管理器-->
    <bean id="transactionManager" class="com.spring.utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils"/>
    </bean>
    <!--代理对象工厂-->
    <bean id="proxyFactory" class="com.spring.factory.ProxyFactory">
        <property name="transactionManager" ref="transactionManager"/>
    </bean>

    <bean id="accountDao" class="com.spring.dao.AccountDaoImpl">
        <property name="connectionUtils" ref="connectionUtils"/>
    </bean>

    <bean id="accountService" class="com.spring.service.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
</beans>

创建BeanFactory来读取解析bean.xml中的bean

public class BeanFactory {

    private static HashMap<String, Object> beanMap = new HashMap<>();

    static {
        try {
            //读取beans xml配置文件
            InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();
            //解析所有bean标签,并放入map中
            List<Element> beanList = rootElement.selectNodes("//bean");
            for (Element element : beanList) {
                String id = element.attributeValue("id");
                String className = element.attributeValue("class");
                Class<?> aClass = Class.forName(className);
                Object o = aClass.newInstance();
                beanMap.put(id, o);
            }

            //解析bean的依赖标签property,并通过set方法注入到对应的类中
            List<Element> properties = rootElement.selectNodes("//property");
            for (Element property : properties) {
                Element parent = property.getParent();
                String id = parent.attributeValue("id");
                Object parentObj = beanMap.get(id);
                Method[] methods = parentObj.getClass().getDeclaredMethods();
                //找到set方法,注入
                List<Method> methodList = Arrays.stream(methods).filter(w -> {
                    String methodName = "set" + property.attributeValue("name");
                    return w.getName().equalsIgnoreCase(methodName);
                }).collect(Collectors.toList());
                if (methodList.size() <= 0) {
                    throw new RuntimeException("依赖对象未找到");
                }
                String ref = property.attributeValue("ref");
                Object childObj = beanMap.get(ref);
                methodList.get(0).invoke(parentObj, childObj);
            }
        } catch (DocumentException | InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过bean name获取bean
     *
     * @param name bean name
     * @return bean对象
     */
    public static Object getBean(String name) {
        return beanMap.get(name);
    }
}

创建事务管理类

public class TransactionManager {

    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * 开启事务
     *
     * @throws SQLException
     */
    public void beginTransaction() throws SQLException {
        System.out.println("begin transaction");
        connectionUtils.getCurrentThreadConn().setAutoCommit(false);
    }

    /**
     * 提交事务
     *
     * @throws SQLException
     */
    public void commit() throws SQLException {
        System.out.println("commit transaction");
        connectionUtils.getCurrentThreadConn().commit();
    }

    /**
     * 回滚事务
     *
     * @throws SQLException
     */
    public void rollback() throws SQLException {
        System.out.println("rollback transaction");
        connectionUtils.getCurrentThreadConn().rollback();
    }
}

创建代理工厂用于在执行service层方法前后进行事务的处理

public class ProxyFactory {

    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public Object getProxy(Object o) {
        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    Object invoke = null;
                    try {
                        //开启事务
                        transactionManager.beginTransaction();
                        invoke = method.invoke(o, args);
                        //关闭事务
                        transactionManager.commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        //回滚事务
                        transactionManager.rollback();
                    }
                    return invoke;
                });
    }
}

接下来我们编写测试类,来看下验证一下我们的项目配置是否正常

先来测试一下dao层,看数据是否可以正常获取

public class AccountDaoImplTest {

    @Test
    public void getAccountByCartId() {
        AccountDao accountDao = (AccountDao) BeanFactory.getBean("accountDao");
        Account account = accountDao.getAccountByCartId("622001");
        System.out.println(account);
    }

    @Test
    public void updateAccount() {
    }
}

看下结果,账户数据可以正常打印,说明我们的bean已经注入成功
在这里插入图片描述

再来看下是否可以转账成功

public class AccountServiceImplTest {

    @Test
    public void transferMoney() {
        ProxyFactory proxyFactory = (ProxyFactory) BeanFactory.getBean("proxyFactory");
        AccountService accountService = (AccountService) proxyFactory.getProxy(BeanFactory.getBean("accountService"));
        accountService.transferMoney("622001", "622002", 100);

    }
}

可以看到已经执行了我们事务中的方法,已经打印出来
在这里插入图片描述
我们再来获取一下账户数据,可以发现钱已经转过去了
在这里插入图片描述
至此我们的项目完整结束

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值