关于项目中用aop写日志和事务的操作

根据aop写日志,这个并不陌生,但是究竟怎么写,需要对aop深刻理解才行!

需要引入包:UserAgentUtils-1.20.jar

在配置中写入aop

         <!--开始配置第一个数据源-->
 <!-- 声明第一个数据源,声明第一个数据库的连接信息 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${dataSource.driverClassName}"></property>
<property name="jdbcUrl" value="${dataSource.url}"></property>
<property name="user" value="${dataSource.username}"></property>
<property name="password" value="${dataSource.password}"></property>
<!-- 指定数据库的最大连接数 -->
<property name="maxPoolSize" value="40"></property>
<!-- 指定数据库的最小连接数 -->
<property name="minPoolSize" value="1"></property>
<!-- 制定数据库的初始化连接数 -->
<property name="initialPoolSize" value="1"></property>
<!-- 指定数据库的最大空闲时间 -->
<property name="maxIdleTime" value="20"></property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="6"></property>
</bean>

        <!-- 注解式事务的支持 -->  
    <tx:annotation-driven transaction-manager="transactionManager"  order="2"/>  
     <!-- 配置事务的传播特性 -->
   <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="edit*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="modify*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="execute*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="get*" propagation="NOT_SUPPORTED" read-only="true" />
            <tx:method name="list*" propagation="NOT_SUPPORTED" read-only="true" />
            <tx:method name="query*" propagation="NOT_SUPPORTED" read-only="true" />
             <tx:method name="find*" propagation="NOT_SUPPORTED" read-only="true" />
            <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
        </tx:attributes>
    </tx:advice>
  <!--   配置那些类、方法纳入到事务的管理 -->
<aop:config>
<aop:pointcut expression="execution (* com.controller..*.*(..))"
id="allserviceMethod" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allserviceMethod" order="2"/>
</aop:config>
        <bean id="jdbcTemp" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg>
<ref bean="dataSource" />
</constructor-arg>
</bean> 

        <!--   引入日志切面  -->
<bean id="logAspect" class="com.service.aop.LogAspect">
</bean>
<aop:config>
<!-- 1.通过aop配置切入点 -->
<aop:pointcut expression="execution(* com.service.*.*(..))" id="servicePointcut"/>
<!-- 2.编织处理 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/>
<aop:advisor advice-ref="logAspect" pointcut-ref="servicePointcut"/>
</aop:config>

直接上代码:


package com.service.aop;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.dao.DataSource;
import com.dao.system.AbsBaseDao;
import com.domain.permission.Oplog;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.utils.ChangeDataSource;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;


public class LogAspect implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
// TODO Auto-generated method stub
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
String token = request.getParameter("token");
//文件上传专属Token
Object strTokenString =  request.getAttribute("token");
String userTokenString ="";
Long id =null;
String reString ="";
//登陆操作
if(token == null){
if(strTokenString== null){
Object object  = invocation.proceed();
if(!"fail".equals(object)){
userTokenString = object.toString();
 String string = request.getSession().getServletContext().getAttribute(userTokenString).toString();
 if (string!=null) {
  String[] split = string.split("_");
  id = Long.parseLong(split[0]);
 }
}else{
reString = "失败";
}
//非登录操作(登陆过)
  }else{
  userTokenString = strTokenString.toString();
 String string = request.getSession().getServletContext().getAttribute(userTokenString).toString();
 if (string!=null) {
  String[] split = string.split("_");
  id = Long.parseLong(split[0]);
 }
  }
}else{
String string = request.getSession().getServletContext().getAttribute(token).toString();
if (string!=null) {
  String[] split = string.split("_");
  id = Long.parseLong(split[0]);
 }
}
HttpSession session = request.getSession();
String ip = InetAddress.getLocalHost().getHostAddress().toString();
UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));  
   //获得操作系统
OperatingSystem os = userAgent.getOperatingSystem();
String logOs = os.getName();
//获得浏览器
Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
String logBrowser = browser.getName();
//获得方法上的注解
String description = "";
String moduleNameString ="";
//目标类的执行结果
Object object = null;
String[] split = null;
String idString = "";
try {
Method method = invocation.getMethod();
object = invocation.proceed();
Object[] objects = invocation.getArguments();
LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
description  = annotation.LogDescription();
moduleNameString = annotation.moduleType();
Oplog  oplog = new Oplog();
oplog.setModuleName(moduleNameString);
oplog.setLogBrowser(logBrowser);
oplog.setLogIp(ip);
oplog.setLogOs(logOs);
oplog.setLogRemarks(description+reString);
Date date =new Date();
Timestamp timestamp = new Timestamp(date.getTime());
oplog.setLogTime(timestamp);
short logType = 0;
oplog.setLogType(logType);
//假数据
oplog.setUsers(id);
ChangeDataSource.changeDataSource(DataSource.dataSource2);
//将日志信息存入数据库
Serializable save = AbsBaseDao.sessionFactory.openSession().save(oplog);

} catch (Exception e) {
e.printStackTrace();
}
return object;
}

}

package com.service.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;


@Target({ElementType.PARAMETER, ElementType.METHOD})      
@Retention(RetentionPolicy.RUNTIME)      
public @interface LogAnnotation {
String LogDescription() default "";
String moduleType() default "";

}

最后需要在每个service方法上加入注解

@LogAnnotation(LogDescription = "获取用户列表",moduleType="授权管理")




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值