目标类
public class B {    @Inject    public B() {    }        public String getName(){        return "BBBBBBB";    }}module类@Modulepublic class AModule {    //单例获取    @Singleton    @PRovides    A providesA(){        return new A();    }}component类@Singleton@Component(modules = AModule.class)public interface AComponent {    void inject(NewActivity act);}activitypublic class NewActivity extends AppCompatActivity {    @Inject    A a1;    @Inject    A a2;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_new);        //实例化component对象        AComponent component = DaggerAComponent.builder().aModule(new AModule()).build();        //注入        component.inject(this);        //single单例只适用于一个component,也就是说下一个activity中又是不同的对象了        Log.e("---------",a1.toString()+"           "+a2.toString());    }}打印结果为:com.iwith.dagger.xinde.A@d1f1395           com.iwith.dagger.xinde.A@d1f1395
注意点:
1:module中需要添加@singleton
2:component需要添加@singleton,不然会编译不过
3:这个只能在同个activity中,如果在另一个activity中的话,创建的实例就会使另一个了,不会是单例了,可见,@singleton只对一个component有效,即其单例所依赖component对象
新闻热点
疑难解答