AndroidAnnotations는 어떤 객체에 대한 주입(injection)이 완료된 이후에 코드를 실행할 수 있는 @AfterInject 어노테이션을 제공합니다. 

그리고  GuiceyFruitMycilaGuice 같은 라이브러리도 인젝션에 대한 콜백을 받을 수 있는 JSR250의 @PreDestroy, @PostConstruct 어노테이션을 구현하여 제공합니다.

그러나 대표적인 안드로이드용 Injection 프레임워크인 RoboGuice는 객체가 생성되고 필드에 대한 주입이 모두 끝난 이후 지정된 메소드(ex. 초기화 메소드)를 실행하는 깔끔한 방법을 제공하지 않습니다. 


다행히 방법이 전혀 없는 것은 아닙니다. 2가지 방법이 존재합니다.


1. InjectionListener를 이용

유연한 방법은 아니지만 Guice의 InjectionListener를 구현하여 주입이후에 지정된 메소드를 실행하게 할 수 있습니다.

(아래 코드에서는 MyInitClass 객체에 대한 모든 주입이 끝나고 나서 init 메소드를 실행합니다)


bindListener(Matchers.subclassesOf(MyInitClass.class), new TypeListener() {

    @Override

    public <I> void hear(final TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {

        typeEncounter.register(new InjectionListener<I>() {

            @Override

            public void afterInjection(Object i) {

                MyInitClass m = (MyInitClass) i;

                m.init();

            }

        });

    }

});



2. @Inject를 이용

Guice는 필드에 대한 모든 주입을 끝내고 나면 @Inject가 붙은 메소드를 실행한다고 합니다. 


    @Inject

    protected void init() {

       ... ...

    }


이 방법은 약간의 트릭에 해당하지만 매우 간단하기 때문에 저는 이 방법을 사용합니다. 자세한 내용은 다음 링크를 참고하세요.


http://stackoverflow.com/questions/2093344/guice-call-init-method-after-instantinating-an-object



Posted by 에코지오
,

RoboGuice 사용환경에서 AspectJ의 aspect 클래스에 모듈을 injection하는 방법입니다.



방법1. static 방식으로 injection


(1) 애스펙트 클래스에서 static 멤버변수로 선언

주입할 모듈을 static 멤버변수로 선언합니다.


 @Inject protected static ContextScopedProvider<T> tProvider; // T는 @ContextSingleton이어야함

 @Inject protected static ExceptionHandler exceptionHandler;//Singleton


(2) Guice 모듈 설정에서 static injection 처리

configure() 메소드에서 requestStaticInjection 메소드를 통해 주입합니다.


requestStaticInjection(ExceptionHandlingAspect.class);


그러나 이 방법은 권장하지 않습니다. Guice에서도 static injection은 deprecated될 것이라고 합니다.

http://code.google.com/p/google-guice/wiki/AvoidStaticState



방법 2. aspect 객체를 구하여 injection


aspect는 AspectJ에 의해 인스턴스화되며 우리가 직접 생성할 수 없습니다. 대부분의 경우 aspect는 싱글턴 객체이며, AspectJ는 싱글턴 aspect 객체를 참조할 수 있는 Aspects.aspectOf() 메소드를 제공합니다.


(1) 주입할 모듈을 애스펙트 클래스에 보통의 멤버변수로 선언


 @Inject protected ExceptionHandler exceptionHandler;


(2) Guice 모듈 설정에서 requestInjection을 통해 injection 처리


requestInjection(org.aspectj.lang.Aspects.aspectOf(ExceptionHandlingAspect.class));


참고:

Posted by 에코지오
,