我在我的项目中使用spring和ibatis,这是我的问题。
我想跟踪所有更改,例如添加/更新/删除
,并将它们记录到表T_TRACE_LOG
中。该表包含以下列:operation_type、object_type、log_content、log_date
。
这是一个示例记录:
"add", "customer", "name='andy',age=23,...", 2012-06-14 17:04:57.410
log_content来自Customer.toString()
,我希望这个过程自动进行,所以我想到了AOP。
我无法控制客户端代码,因为有些使用 addCustomer()
,有些使用 insertCustomer()
,还有一些使用 createCustomer()
>。但最后他们都调用了 getSqlMapClientTemplate().insert("inserCustomer", Customer)
。所以我想在 getSqlMapClientTemplate().insert()
上切入点以匹配它们。
这是我的尝试,但它不起作用:
<aop:pointcut expression="execution(* org.springframework.orm.ibatis.SqlMapClientTemplate.insert(..))" id="insertLogPointCut"/>
如果我将表达式更改如下,它会起作用:
<aop:pointcut expression="execution(* com.xxx.CustomerDaoImpl.insert(..))" id="logPointCut"/>
因为AOP根据源代码将“切入点信息”编译成类字节码,所以我认为不可能在ibatis类上进行切入点。如果错了,我的情况该如何处理?
这是配置:
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="traceLogger" class="com.xx.TraceLogger"/>
<aop:config>
<aop:pointcut expression="execution(* com.xx.CustomerDaoImpl.insert(..))" id="insertLogPointCut"/>
<aop:aspect id="logAspect" ref="traceLogger">
<aop:after-returning method="logAfterReturning" pointcut-ref="insertLogPointCut"/>
</aop:aspect>
</aop:config>
最佳答案
Spring 中的默认 AOP 行为仅适用于接口(interface)(因为它使用 Java 的动态代理)。如果切入点设置在具体类上,它将不起作用。
SqlMapClientTemplate,如果我没记错的话,是一个类。
你可以选择
- 使用 cg-lib 创建代理,或
- 更改您的 bean 以使用 SqlMapClientOperations 而不是 SqlMapClientTemplate,并将切入点写入“execution(* org.springframework.orm.ibatis.SqlMapClientOperations.insert(..))”
我推荐方法2。
而且,你的猜测是错误的。 AOP相关的东西没有编译成相应的字节码。它们都是在运行时完成的(对于 Spring 中的情况)
关于java - 是否可以在第三方类上切入点以及如何切入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11030358/