mawenjian
V2EX  ›  问与答

一个使用 Spring AOP 和注解实现( MyBatis)数据库读写分离的问题

  •  
  •   mawenjian · Jul 30, 2015 · 6252 views
    This topic created in 3951 days ago, the information mentioned may be changed or developed.
    原文: http://www.cnblogs.com/surge/p/3582248.html。

    这篇文章的原理就是利用Spring AOP对DAO层中的方法的注解值进行判断,然后使用不同的DataSource,进而实现数据库的读写分离。

    比如:
    public interface UserMapper {
    @DataSource("master")
    public void add(User user);
    @DataSource("slave")
    public List<User> list();
    }
    利用@DataSource注解,就会分别从两个数据源读/写数据。

    下面是注解:
    <!-- 配置数据库注解aop -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <beans:bean id="manyDataSourceAspect" class="com.abc.proxy.DataSourceAspect" />
    <aop:config>
    <aop:aspect id="c" ref="manyDataSourceAspect">
    <aop:pointcut id="tx" expression="execution(* com.abc.mapper.*.*(..))"/>
    <aop:before pointcut-ref="tx" method="before"/>
    </aop:aspect>
    </aop:config>
    <!-- 配置数据库注解aop -->

    但是我在按照这个教程配置的过程中,发现这个配置是走不通的。因为@DataSource是针对方法级别的,但是determineCurrentLookupKey方法为SqlSessionFactory等类的构造中需要的,执行顺序是determineCurrentLookupKey->before,所以annotation方法就失效了?请问应当如何处理?

    当然,用别的方式实现也行。多谢!
    1 replies    2018-04-16 13:30:19 +08:00
    pucika
        1
    pucika  
       Apr 16, 2018   ❤️ 1
    切面切不到具体的 class, mapper 紧定义了 interface。要么包一层 service,要么看怎么能在具体的实现类做切面。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2926 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 466ea39e · 35ms · UTC 08:26 · PVG 16:26 · LAX 01:26 · JFK 04:26
    ♥ Do have faith in what you're doing.