java - Dagger2: Using factory methods in place of public constructors -
i trying use public factory methods in place of public constructors dagger2. think missing connection in using dagger2.
when use public constructors, example interfaces / classes follows:
interface interfacea { void foo(); } class implements interfacea { @inject public a() {} @override public void foo() { system.out.println("foo"); } } interface interfaceb { void bar(); } class b implements interfaceb { private final interfacea depa; @inject public b(interfacea depinstance) { depa = depinstance; } @override public void bar() { system.out.println("bar"); depa.foo(); } } @module class mymodule { @provides interfacea providea(final provider<a> provider) { return a.create(provider); } @provides interfaceb provideb(b binstance) { return binstance; } } @component(modules=mymodule.class) interface mycomponent { interfacea provideinterfacea(); interfaceb provideinterfaceb(); }
usage above:
public class test { public static void main(string[] args) { mycomponent comp = daggermycomponent.create(); interfacea = comp.provideinterfacea(); a.foo(); interfaceb b = comp.provideinterfaceb(); b.bar(); } }
now, if rewrite classes , b follows:
class implements interfacea { public static create() { return new a(); } private a() {} @override public void foo() { system.out.println("foo"); } } class b implements interfaceb { public static b create(interfacea depa) { return new b(depa); } private final interfacea depa; private b(interfacea depinstance) { depa = depinstance; } @override public void bar() { system.out.println("bar"); depa.foo(); } }
i able re-write mymodule class as:
@module class mymodule { @provides interfacea providea() { return a.create(); } @provides interfaceb provideb() { return b.create(providea()); } }
but not use of dagger2 framework. looks not writing classes use inject , provides annotations correctly. missing?
you're pretty close, you're making minor mistakes though. should provide instance provider method using method parameter, otherwise you'd create multiple instances in case of scoped provider. , can use void inject(something something);
if want.
@module class mymodule { @provides interfacea providea() { return a.create(); } @provides interfaceb provideb(interface interfacea) { return b.create(interfacea); } } @component(modules=mymodule.class) interface mycomponent { interfacea provideinterfacea(); interfaceb provideinterfaceb(); void inject(test test); } public class test { @inject interfacea a; @inject interfaceb b; public static void main(string[] args) { mycomponent comp = daggermycomponent.create(); comp.inject(this); a.foo(); b.bar(); } }
Comments
Post a Comment