AOP通知的使用
- 一、业务层接口万次执行效率
- 1、需求分析
- 2、实现思路
- 3、示例演示
- 1)依赖准备
- 2)数据访问层、业务逻辑层准备
- 3)配置类准备
- 4)通知类准备
- 5)方法测试
- 6)测试结果
- 二、通过AOP通知获取数据
- 1、哪些通知能够获取数据?
- 2、获取参数
-
- 3、获取返回值
-
- 4、获取异常
-
一、业务层接口万次执行效率
1、需求分析
- 计算业务层接口万次执行效率,效率使用执行时间表示。
- 通过执行时间来监控出哪个业务时比较耗时的,可以对该业务代码进行优化。
2、实现思路
- 在方法执行前记录一个时间
- 执行方法
- 在方法执行完后再记录一个时间
- 用后一个时间减去前一个时间的差值,就是我们万次执行时间。
- 通过分析之后,选择使用 环绕通知 来实现该需求。
- 因为Java的执行效率还是比较快的,如果只执行一次原始方法,无法显著看出执行效率,故建议统计万次执行效率。
3、示例演示
1)依赖准备
org.springframework
spring-context
5.3.16
org.aspectj
aspectjweaver
1.9.9.1
com.alibaba
druid
1.1.17
mysql
mysql-connector-java
8.0.28
org.springframework
spring-jdbc
5.3.16
org.mybatis
mybatis-spring
2.0.7
org.mybatis
mybatis
3.5.9
junit
junit
4.12
test
org.springframework
spring-test
5.3.16
2)数据访问层、业务逻辑层准备
@Repository
public interface UserMapper {
@Select("select * from user where id = #{id}")
public User selectById(Integer id);
@Select("select * from user")
public List selectAll();
}
public interface UserService {
public User selectById(Integer id);
public List selectAll();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
public User selectById(Integer id) {
User user = userMapper.selectById(id);
return user;
}
public List selectAll() {
List users = userMapper.selectAll();
return users;
}
}
3)配置类准备
- 因为在开发中更多的会使用注解来开发,所以博主将许多应该在 xml 配置文件中的内容通过编写配置类的方式实现了。不了解的小伙伴可以浏览博主 Spring专栏 查看相关内容,相信您一定会有所收获。
// 连接数据库
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
}
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("pojo");
ssfb.setDataSource(dataSource);
return ssfb;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("mapper");;
return msc;
}
}
// Spring配置类
@Configuration
@ComponentScan({"mapper","advice","service"})
@EnableAspectJAutoProxy // 开启注解格式的AOP功能
@PropertySource({"jdbc.properties"})
@Import({JdbcConfig.class,MyBatisConfig.class})
public class SpringConfig {
}
4)通知类准备
@Component
@Aspect
public class UserAdvice {
@Pointcut("execution(* service.*Service.*(..))")
public void pt(){};
@Around("pt()")
public void around(ProceedingJoinPoint pjp) throws Throwable {
// 获取执行签名信息
Signature signature = pjp.getSignature();
// 获取接口名
String className = signature.getDeclaringTypeName();
// 获取方法名
String methodName = signature.getName();
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++){
pjp.proceed();
}
long end = System.currentTimeMillis();
System.out.println("万次执行:" + className + "." + methodName + "---->" + (end - begin) + "ms");
}
}
- ProceedingJoinPoint 对象中记录了许多信息,上述三个是较为常用的,可以通过调用相关方法获取当前执行方法的信息。
5)方法测试
// 设置类运行器
@RunWith(SpringJUnit4ClassRunner.class)
// 设置Spring环境对应的配置类
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testSelectById(){
userService.selectById(3);
userService.selectAll();
}
}
6)测试结果
- 当前测试的执行效率仅仅是一个理论值,并不是一次完整的执行过程。在开发中还需要具体问题具体分析。
二、通过AOP通知获取数据
1、哪些通知能够获取数据?
- 对于切入点方法的参数,所有的通知类型都能够获取
- JoinPoint :适用于前置、后置、返回后、抛出异常后通知
- ProceedingJoinPoint :适用于环绕通知
- 对于切入点方法的返回值,前置通知和抛出异常后通知是没有返回值,后置通知可有可无,不做研究。只研究 返回后通知 和 环绕通知 。
- 对于切入点方法运行异常信息,前置和返回后通知是不会有,后置通知可有可无,不做研究。只研究 抛出异常后通知 和 环绕通知 。
2、获取参数
1)非环绕通知
@Component
@Aspect
public class UserAdvice {
@Pointcut("execution(* service.*Service.*(..))")
public void pt(){};
@Before("pt()")
public void before(JoinPoint jp){
Object[] args = jp.getArgs();
System.out.println(Arrays.toString(args));
}
}
- 在前置方法中添上形参对象 JoinPoint ,通过调用其提供的方法获取参数。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void test(){
userService.selectById(2);
}
}
2)环绕通知
- 环绕通知拥有自己特定的参数对象 ProceedingJoinPoint ,同时该对象也会定义相应的方法。
@Component
@Aspect
public class UserAdvice {
@Pointcut("execution(* service.*Service.*(..))")
public void pt(){};
@Around("pt()")
public void around(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
System.out.println(Arrays.toString(args));
}
}
3、获取返回值
1)环绕通知
@Component
@Aspect
public class UserAdvice {
@Pointcut("execution(* service.*Service.*(..))")
public void pt(){};
@Around("pt()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
Object proceed = pjp.proceed();
return proceed;
}
}
- 调用 proceed 方法会得到一个返回值,返回的对象即为原始方法的返回值。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void test(){
System.out.println(userService.selectById(3));
}
}
- 测试后会返回 id = 3 的用户信息。
- 除了空参的 proceed 方法外,还存在有带参的 proceed 方法。
可以调用带参的 proceed 方法,修改原始参数。
@Component
@Aspect
public class UserAdvice {
@Pointcut("execution(* service.*Service.*(..))")
public void pt(){};
@Around("pt()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
args[0] = 2;
Object proceed = pjp.proceed(args);
return proceed;
}
}
- 修改原始参数了,不修改测试代码,再次执行后会发现返回的数据发生了改变。
因为不存在 id = 2 的用户,所以返回 null 。
2)返回后通知
@Component
@Aspect
public class UserAdvice {
@Pointcut("execution(* service.*Service.*(..))")
public void pt(){};
@AfterReturning(value = "pt()",returning = "ret")
public void afterReturning(Object ret){
System.out.println("AfterReturning ... " + ret);
}
}
- @AfterReturning 注解中使用 returning 指定返回值名称,且需要与形参名称保持一致,返回结果如下所示。
- 如果还需要通过使用 JoinPoint 来获取参数得内容,形参中需要优先将 JoinPoint 放到前面。
public void afterReturning(JoinPoint jp,Object ret){...}
4、获取异常
1)环绕通知
@Component
@Aspect
public class UserAdvice {
@Pointcut("execution(* service.*Service.*(..))")
public void pt(){};
@Around("pt()")
public void around(ProceedingJoinPoint pjp){
try {
Object proceed = pjp.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
- 环绕通知获取异常的方式非常简单,之前我们在写环绕通知时都是将异常抛出,为了获取到异常类型,在写环绕通知时不再采用抛出的,而是手动将其捕捉到即可。
2)抛出异常后通知
@Component
@Aspect
public class UserAdvice {
@Pointcut("execution(* service.*Service.*(..))")
public void pt(){};
@AfterThrowing(value = "pt()",throwing = "t")
public void afterThrowing(Throwable t){
System.out.println("AfterThrowing ... " + t);
}
}
- @AfterThrowing 注解中使用 throwing 指定异常名称,需要与方法形参名相同。
- 同样,如果涉及到 JoinPoint 参数,需将其方法最前面。