Google Guice - AOP
AOP,面向方面的编程需要将程序逻辑分解为不同的部分,称为所谓的关注点。 跨越应用程序多个点的功能称为横切关注点,这些横切关注点在概念上与应用程序的业务逻辑是分开的。 日志记录、审计、声明性事务、安全性、缓存等方面有各种常见的好例子。
OOP 中模块化的关键单元是类,而 AOP 中模块化的单元是方面。 依赖注入可以帮助您将应用程序对象彼此解耦,AOP 可以帮助您将横切关注点与其影响的对象解耦。 AOP 就像 Perl、.NET、Java 等编程语言中的触发器。 Guice 提供拦截器来拦截应用程序。 例如,当执行一个方法时,您可以在方法执行之前或之后添加额外的功能。
重要类
Matcher - 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

