Spring-AOP 示例 环绕增强 日志记录
1. 创建商品日志记录表 Product_Log
create sequence seq_product_log start with 1;
select * from product_log;
create table product_log(
pl_id number primary key, --主键
action_class varchar2(50), --始发类
method_name varchar2(50), --方法名
args varchar2(100), --参数集
create_date date default sysdate
)SEGMENT CREATION IMMEDIATE;
2. 完成日志记录表的插入逻辑
<mapper namespace="com.gxy.dao.ProductLogDao">
<!-- 通用结果集映射-->
<resultMap type= "com.gxy.entity.ProductLog" id= "BaseResultMap">
<id column="pl_id" property="piId"/>
<result column="action_class" property="actionClass"/>
<result column="method_name" property ="methodName"/>
<result column="args" property="args"/>
<result column="create_date" property="createDate"/>
</resultMap>
<!-- 日志记录 -->
<insert id="insertLog">
insert into product_log(pl_id,action_class,method_name,args)
values(seq_product_log.nextval,#{actionClass},#{methodName},#{args})
</insert>
</mapper>
3. 环绕增强搜集日志记录参数,并测试
<!-- 增强功能 -->
<bean id="myInterceptor" class="com.gxy.aop.MyInterceptor"></bean>
<!-- AOP配置 编织 -->
<aop:config>
<aop:pointcut expression="execution(* com.gxy.service.ProductService.*(..))" id="myPointCut"/>
<aop:advisor advice-ref="myInterceptor" pointcut-ref="myPointCut"/>
</aop:config>
4. 环绕增强调用日志记录表的插入逻辑,完成日志记录功能
public class MyInterceptor implements MethodInterceptor{
@Override
public Object invoke(MethodInvocation arg0) throws Throwable {
//获取目标实现类对象
String actionClass = arg0.getThis().getClass().toString();
//获取目标方法名称
String methodName = arg0.getMethod().getName();
//获取目标方法参数的实参列表
String args="";
Object[] arguments = arg0.getArguments();
for (int i = 0; i < arguments.length; i++) {
System.out.println("arg0.getArguments():"+arguments[i]);
//参数的拼接
args = args + "-" +arguments[i] ;
}
args = args.replaceFirst("-", "");
//加载Spring主配置文件 创建工厂
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ProductLogService productLogService = (ProductLogService) context.getBean("productLogService");
ProductLog productLog = new ProductLog();
productLog.setActionClass(actionClass);
productLog.setArgs("args");
productLog.setMethodName(methodName);
int i = productLogService.addLog(productLog);
//执行目标原方法
Object object = arg0.proceed();
return object;
}
}
@Test
public void method3() throws IOException{
//加载Spring主配置文件 创建工厂
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//根据Bean ID,由工厂创建对象
ProductService productService = (ProductService) context.getBean("productService");
Product product = productService.selectProductById(1);
System.out.println(product);
}