Google Guice - AOP

AOP,面向方面的编程需要将程序逻辑分解为称为所谓关注点的不同部分.跨越应用程序多个点的功能称为跨领域问题,这些跨领域问题在概念上与应用程序的业务逻辑分离.有各种常见的好例子,例如日志记录,审计,声明式事务,安全性,缓存等.

OOP中模块化的关键单元是类,而在AOP中的单位是模块化是方面.依赖注入可以帮助您将应用程序对象相互分离,AOP可以帮助您将交叉问题与它们所影响的对象分离. AOP就像Perl,.NET,Java等编程语言中的触发器. Guice提供拦截器来拦截应用程序.例如,当执行方法时,您可以在方法执行之前或之后添加额外的功能.

重要类

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

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

示例

创建一个名为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

之后