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));
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容