测定接口执行效率
描述:在接口执行前输出当前系统时间
开发模式:XML or 注解
思路分析:
1.导入坐标(pom.xml)
<dependencies><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.4</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.25.RELEASE</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency></dependencies>
2.制作连接点的方法(原始操作)
package org.example.dao;public interface BookDao {void save();void update();
}
package org.example.dao.impl;import org.example.dao.BookDao;
import org.springframework.stereotype.Repository;@Repository
public class BookDaoImpl implements BookDao {public void save() {System.out.println("book dao save");System.out.println(System.currentTimeMillis());}public void update() {System.out.println("book dao update");}public void delete() {System.out.println("book dao delete");}public void select() {System.out.println("book dao select");}
}
4.定义切入点
package org.example.aop;import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;@Component
@Aspect//当作Aop处理
public class MyAdvice {@Pointcut("execution(void org.example.dao.BookDao.update())")private void pt(){}@Before("pt()")public void method(){System.out.println(System.currentTimeMillis());}
}
5.注解驱动支持
package org.example.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;@Configuration
@ComponentScan("org.example")
@EnableAspectJAutoProxy//有用注解开发的AOP
public class SpringConfig {
}
测试
package org.example;import org.example.config.SpringConfig;
import org.example.dao.BookDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;/*** Hello world!**/
public class App
{public static void main( String[] args ){ApplicationContext ctx=new AnnotationConfigApplicationContext(SpringConfig.class);BookDao bookDao=ctx.getBean(BookDao.class);bookDao.save();bookDao.update();}
}