学习 Guice(三):Spark 切面编程实践

定义注解

用于标注需要启用测量 Spark 指标的方法

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EnableMeasure {}  

定义方法拦截器

class MeasureInterceptor extends MethodInterceptor {

  @Inject
  private var spark: SparkSession = _

  override def invoke(invocation: MethodInvocation): AnyRef = {
    val listener = new MeasureSparkListener
    spark.sparkContext.addSparkListener(listener)
    val ret = invocation.proceed()
    ret
  }
}

绑定

在 Module 的 configure 方法中,将拦截器与注解进行绑定:

val measureInterceptor = new MeasureInterceptor  
requestInjection(measureInterceptor)  
bindInterceptor(Matchers.any, Matchers.annotatedWith(classOf[EnableMeasure]), measureInterceptor) // 绑定注解  

使用

注入

val injector = Guice.createInjector(module, new ApplicationModule)  
injector.getInstance(classOf[Application]).run()  

启用

class Application {

  @EnableMeasure
  def run(): Unit = {
    // TODO
  }

}