Google Guice - AOP




AOP,面向切面编程,它将程序逻辑分解成不同的部分,称为“关注点”。跨越应用程序多个点的功能称为横切关注点,这些横切关注点在概念上与应用程序的业务逻辑是分开的。一些常见的方面示例包括日志记录、审计、声明式事务、安全、缓存等。

OOP 中模块化的关键单元是类,而在 AOP 中,模块化的单元是方面。依赖注入帮助你解耦应用程序对象,而 AOP 帮助你解耦横切关注点与其影响的对象。AOP 就像 Perl、.NET、Java 等编程语言中的触发器。Guice 提供拦截器来拦截应用程序。例如,当执行方法时,你可以在方法执行之前或之后添加额外功能。

重要类

  • Matcher - Matcher 是一个接口,用于接受或拒绝值。在 Guice AOP 中,我们需要两个匹配器:一个用于定义参与的类,另一个用于这些类的特定方法。

  • MethodInterceptor - 当调用匹配的方法时,将执行 MethodInterceptor。它们可以检查调用:方法、参数和接收实例。我们可以执行横切逻辑,然后委托给底层方法。最后,我们可以检查返回值或异常并返回。

示例

创建一个名为 GuiceTester 的 Java 类。

GuiceTester.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.matcher.Matchers;

public class GuiceTester {
   public static void main(String[] args) {
      Injector injector = Guice.createInjector(new TextEditorModule());
      TextEditor editor = injector.getInstance(TextEditor.class);
      editor.makeSpellCheck(); 
   } 
}

class TextEditor {
   private SpellChecker spellChecker;

   @Inject
   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }

   public void makeSpellCheck(){
      spellChecker.checkSpelling();
   }
}

//Binding Module
class TextEditorModule extends AbstractModule {

   @Override
   protected void configure() {
      bind(SpellChecker.class).to(SpellCheckerImpl.class);
      bindInterceptor(Matchers.any(), 
         Matchers.annotatedWith(CallTracker.class), 
         new CallTrackerService());
   } 
}

//spell checker interface
interface SpellChecker {
   public void checkSpelling();
}

//spell checker implementation
class SpellCheckerImpl implements SpellChecker {

   @Override @CallTracker
   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   } 
}

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

class CallTrackerService implements MethodInterceptor  {

   @Override
   public Object invoke(MethodInvocation invocation) throws Throwable {
      System.out.println("Before " + invocation.getMethod().getName());
      Object result = invocation.proceed();
      System.out.println("After " + invocation.getMethod().getName());
      return result;
   }
}

输出

编译并运行文件,你可能会看到以下输出。

Before checkSpelling
Inside checkSpelling.
After checkSpelling
广告
© . All rights reserved.