Guice 依赖注入 与 AOP

Guice [https://github.com/google/guice],是 Google 的轻量级依赖注入框架。下面的例子介绍用 Guice 依赖注入和向切面编程(AOP)的方法。

package test.guice;

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;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;

interface Calculator {
    int add(int a, int b);
}

class CalculatorImpl implements Calculator {
    @Override
    public int add(int a, int b) {
        return a + b;
    }
}

interface AccountManager {
    int sum(int a, int b);
}

class AccountManagerImpl implements AccountManager {
    @Inject
    private Calculator calculator;
    @Override
    public int sum(int a, int b) {
        return calculator.add(a, b);
    }
}

class TestInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Method method1 = methodInvocation.getMethod();
        Object thisObj1 = methodInvocation.getThis();

        System.out.println("Before invocation, method name " +
                method1.getName() + ", this obj " +
                thisObj1.getClass().getName());

        Object result = methodInvocation.proceed();

        Method method2 = methodInvocation.getMethod();
        Object thisObj2 = methodInvocation.getThis();

        System.out.println("After invocation, method name " +
                method2.getName() + ", this obj " +
                thisObj2.getClass().getName());

        return result;
    }
}

//Binding Module
class InjectionConfig extends AbstractModule {
    @Override
    protected void configure() {
        bind(Calculator.class).to(CalculatorImpl.class);
        bind(AccountManager.class).to(AccountManagerImpl.class);

        TestInterceptor interceptor = new TestInterceptor();
        bindInterceptor(Matchers.any(), Matchers.any(), interceptor);
    }
}

public class GuiceTester {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new InjectionConfig());
        AccountManager manager = injector.getInstance(AccountManager.class);
        System.out.println("Sum of account is " + manager.sum(3, 5));
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容