Using Dagger for dependency injection on constructors

前端 未结 5 689
故里飘歌
故里飘歌 2021-01-31 17:17

So, I\'m currently redesigning an Android app of mine to use Dagger. My app is large and complicated, and I recently came across the following scenario:

Object A requir

5条回答
  •  悲哀的现实
    2021-01-31 17:48

    Jake's post is great, but there is more simple way. Google created AutoFactory library for creating factory automatically at compile time.

    First, create class A with @AutoFactory annotation and @Provided annotation for injecting arguments:

    @AutoFactory
    public class A {
    
        private DebugLogger logger;
    
        public A(@Provided DebugLogger logger, int amount, int frequency) {
            this.logger = logger;
        }
    }
    

    Then library creates AFactory class at compile time. So you need just inject the factory to a constructor of B class.

    public class B {
    
        private final AFactory aFactory;
    
        @Inject
        public B(AFactory aFactory) {
            this.aFactory = aFactory;
        }
    
        public A createA(int amount, int frequency) {
            return aFactory.create(amount, frequency);
        }
    }
    

提交回复
热议问题