发表于: 2017-07-17 23:55:52

1 1129


今天所做:

思路:统计dao层方法执行时间是访问db的时间。

先写了一条输出到日志中。

public long insert(Student student) {
//Long startTime = System.currentTimeMillis();
  studentDao.insert(student);
  //Long endTime = System.currentTimeMillis();
  //logger.info("此次插入一条数据时间"+(endTime-startTime)+"ms");
  return student.getId();
}


然后用spring aop ,用的配置xml文件方法。

 spring aop 实现方法:

添加依赖:

1、在原有pom文件中添加:

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.9</version>
</dependency>

2.添加spring-aop配置文件到classpath路径。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd"
    <!-- 被代理对象  -->
   <bean id="StudentServiceImpl" class="com.dj.service.impl.StudentServiceImpl" />
   <!--通知-->
   <bean id = "advices" class="aop.Advices"/>
   <!-- aop配置 -->
   <aop:config proxy-target-class="true">
       <!--切面-->
       <aop:aspect ref="advices">
           <!--切点-->
           <aop:pointcut expression="execution(* com.dj.service.impl.StudentServiceImpl.*(..))" id="pointcut1"/>
           <!--连接通知方法与切点 -->
           <aop:before method = "before" pointcut-ref="pointcut1"/>
           <aop:after method = "after" pointcut-ref="pointcut1"/>
       </aop:aspect>
   </aop:config>
</beans>

Springaop切点配置:

带问号的是可选项

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)throws-pattern?)

·         modifier-pattern:表示方法的修饰符

·         ret-type-pattern:表示方法的返回值

·         declaring-type-pattern?:表示方法所在的类的路径

·         name-pattern:表示方法名

·         param-pattern:表示方法的参数

·         throws-pattern:表示方法抛出的异常

 

每个partten可以用 * 号匹配所有,param-pattern:表示方法的参数,参数之间可用逗号隔开,也可用*表示匹配任意类型参数,可以用(..)表示零个或多个任意的方法参数。

3、添加Advices类  

public class Advices {
Long startTime;
   Long endTime;
   private static Logger logger = org.apache.logging.log4j.LogManager.getLogger(Advices.class);
//    private static Logger logger = LogManager.getLogger();
   public void before(JoinPoint jp){
this.startTime= System.currentTimeMillis();
       System.out.println(jp.getSignature().getName());
   }
public void after(JoinPoint jp){
this.endTime = System.currentTimeMillis();
       logger.info(jp.getSignature().getName()+"执行时间为:"+(endTime-startTime)+"ms");

   }
}


明天:

spring aop的注解方式使用。

总结任务三,任务三补充。


返回列表 返回列表
评论

    分享到