我正在使用Dagger 2并希望使用它为Android Studio中的不同构建版本注入不同的依赖项。
public class DemoApplication extends Application{
AppComponent component;
@Override
public void onCreate() {
super.onCreate();
component = DaggerAppComponent.builder().module(new Module()).build();
}
}
@Module
public class Module {
@Provides
@Singleton
public ClassA provideClassA(){
return new ClassA();
}
}
@Component (modules = {Module.class})
public interface AppComponent {
ClassA getClassA();
}
现在假设我希望ClassA的对象返回prod flavor,但是在调试风格中返回ClassB的对象(从ClassA扩展)。
答案 0 :(得分:1)
例如,让我们考虑模拟和生产风格。创建'use strict'
const stockItems = [
{ item: "sword", type: "weapon", weight: "5 lbs.", cost: "10 gold" },
{ item: "hammer", type: "weapon", weight: "8 lbs.", cost: "7 gold" }
];
function isEquivalent(a, b) {
// Create arrays of property names
const aProps = Object.getOwnPropertyNames(a);
const bProps = Object.getOwnPropertyNames(b);
// If number of properties is different,
// objects are not equivalent
if (aProps.length != bProps.length) {
return false;
}
for (let i = 0; i < aProps.length; i++) {
const propName = aProps[i];
// If values of same property are not equal,
// objects are not equivalent
if (a[propName] !== b[propName]) {
return false;
}
}
// If we made it this far, objects
// are considered equivalent
return true;
}
// normal indexof will not work with object because it uses strict equality
function myIndexOf(array, object) {
for (let i = 0; i < array.length; i++) {
if (isEquivalent(array[i], object)) return i;
}
return -1;
}
function getUniqueRandomItem(shopItems) { //from stock
var item;
while (true) {
item = stockItems[Math.floor(Math.random() * stockItems.length)];
if (myIndexOf(shopItems, item) < 0) return item;
}
}
function buildShopItems(count) {
count = stockItems.length < count ? stockItems.length : count;
const shopItems = [];
for (let i = 0; i < count; i++) {
const item = getUniqueRandomItem(shopItems);
shopItems.push(item);
}
return shopItems;
}
const shopItems = buildShopItems(1);
console.log(shopItems);
和mock
目录并将它们放在production
旁边,在main
和Module
目录中放置一个名为mock
的单独类也必须是一样的)。这样,当您切换构建变体时,编译器将引用production
或Module
类中的mock
类,允许您根据风格注入不同的实现。< / p>
查看源集上的此参考:http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Sourcesets-and-Dependencies
这个答案可能也会有所帮助:How the flavor-specific variants are working?