SlideShare a Scribd company logo
Dagger 2
INJEÇÃO DE DEPENDÊNCIA
Injecão de Dependência
 Dependência é qualquer objeto necessário
para o funcionamento de uma classe;
 Desacoplamento entre classes de alto e
baixo nível;
 Inexistente, manual ou automática.
public class ClassA {
private ClassB mClassB;
public ClassA() {
mClassB = new ClassB();
}
}
public class ClassA {
private ClassB mClassB;
public ClassA() {
mClassB = new ClassB(new ClassC());
}
}
public class ClassA {
private ClassB mClassB;
public ClassA(ClassB classB) {
mClassB = classB;
}
}
Bibliotecas
 Guice
 Dagger (v1)
 Dagger 2
 ...
Funcionamento
@Bind(R.id.home_iv) ImageView mImageView;
ButterKnife.bind(this, view);
view mImageView
findViewbyId
@Bind
mImageView = (ImageView)view.findViewbyId(R.id.home_iv);
Funcionamento
Component Object
“findObjectOfTypeX”
@Inject
Module
Exemplo
Retrofit
bit.ly/di-android-meetup
Retrofit Service
public class GitHubApi {
public static final int CACHE_SIZE = 5 * 1024 * 1024;
public static <S> S createService(Class<S> serviceClass, Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
final Gson gson = gsonBuilder.create();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.cache(new Cache(context.getCacheDir(), CACHE_SIZE))
.readTimeout(30, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(BuildConfig.API_URL)
.client(client)
.build();
return retrofit.create(serviceClass);
}
}
UserModel
public class GitHubUserModel {
private final GitHubService mService;
public GitHubUserModel(Context context) {
mService = GitHubApi.createService(GitHubService.class, context);
}
public Call<List<GitHubUser>> fetchUsers(int page) {
return mService.getUsers(page);
}
...
}
GitHubUserModel userModel = new GitHubUserModel(getActivity().getApplicationContext());
mActionInteractor = new UsersListPresenter(this, userModel);
mActionInteractor.loadUsersList(false);
Introduzindo Dagger
Dagger API
 @Module + @Provides
 Mecanismo para prover dependências
 @Inject
 Mecanismo para requisitar dependências
 @Component
 Ligação entre módulos e injeções
Dagger
Project/build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8’
}
}
App/build.gradle
apply plugin: 'com.neenbedankt.android-apt'
compile 'com.google.dagger:dagger:2.0.2'
apt 'com.google.dagger:dagger-compiler:2.0.2'
provided 'org.glassfish:javax.annotation:10.0-b28'
@Module
public class NetworkModule {
public static final int CACHE_SIZE = 5 * 1024 * 1024;
@Provides
public Retrofit provideRetrofit(Gson gson, OkHttpClient client) {
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(BuildConfig.API_URL)
.client(client)
.build();
}
@Provides
public OkHttpClient provideHttpClient(HttpLoggingInterceptor interceptor, Cache cache) {
return new OkHttpClient.Builder()
.addInterceptor(interceptor)
.cache(cache)
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
}
@Provides
public Cache provideCache(Application application) {
return new Cache(application.getCacheDir(), CACHE_SIZE);
}
@Provides
public HttpLoggingInterceptor provideHttpInterceptor() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return interceptor;
}
@Provides
public Gson provideHttpGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
}
@Module
public class GitHubModule {
public interface GitHubService {
@GET("/users")
@Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN)
Call<List<GitHubUser>> getUsers();
@GET("/users/{login}")
@Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN)
Call<GitHubUser> getUser(@Path("login") String login);
@GET("/users")
@Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN)
Call<List<GitHubUser>> getUsers(@Query("since") int page);
}
@Provides
public GitHubService provideGitHubService(Retrofit retrofit) {
return retrofit.create(GitHubService.class);
}
}
@Module
public class AppModule {
private final Context mApplicationContext;
public AppModule(Context applicationContext) {
mApplicationContext = applicationContext;
}
@Provides
@PerApp
public Context provideApplicationContext() {
return mApplicationContext;
}
}
@Component(modules = {AppModule.class, GitHubModule.class, NetworkModule.class})
public interface AppComponent {
void inject(UsersListFragment fragment);
}
DepencyInjectionApplication.java
@NonNull
protected DaggerAppComponent.Builder prepareAppComponent() {
return DaggerAppComponent.builder()
.networkModule(new NetworkModule())
.gitHubModule(new GitHubModule())
.appModule(new AppModule(this));
}
GitHubUserModel.java
public class GitHubUserModel {
private final GitHubModule.GitHubService mService;
@Inject
public GitHubUserModel(GitHubModule.GitHubService service) {
mService = service;
}
...
}
UsersListFragment.java
@Inject public GitHubUserModel mUserModel;
@Override
protected void onCreate() {
DepencyInjectionApplication.getAppComponent(getActivity()).inject(this);
}
@Override
protected void onResume() {
mActionInteractor = new UsersListPresenter(this, mUserModel);
mActionInteractor.loadUsersList(false);
}
GitHubUserModel
Retrofit
OkHttpClient
Gson
NetworkModule#provideRetrofit
NetworkModule#provideHttpClient
NetworkModule#provideGson
GitHubService GitHubModule#provideGitHubService
Component Dependency
@Component(modules={AppModule.class, NetworkModule.class})
public interface NetComponent {
Retrofit retrofit();
}
@Component(dependencies = NetComponent.class, modules = GitHubModule.class)
public interface AppComponent {
void inject(UsersListFragment fragment);
}
public class DepencyInjectionApplication extends Application {
private AppComponent mAppComponent;
private NetComponent mNetComponent;
private void setupDaggerAppComponent() {
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
// .networkModule(new NetworkModule()) is free
.build();
mAppComponent = DaggerAppComponent.builder()
// .gitHubModule(new GitHubModule()) is free
.netComponent(mNetComponent)
.build();
}
}
Subcomponent
@Subcomponent(modules = GitHubModule.class)
public interface GitHubComponent {
void inject(UsersListFragment fragment);
}
@Component(modules = {NetworkModule.class, AppModule.class})
public interface AppComponent {
Application getApplication();
GitHubComponent plus(GitHubModule gitHubModule);
}
DepencyInjectionApplication.java
private void setupDaggerAppComponent() {
mAppComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
UsersListFragment.java
@Override
protected void onCreate() {
DepencyInjectionApplication.getAppComponent(getActivity())
.plus(new GitHubModule())
.inject(this);
}
@Override
protected void onResume() {
mActionInteractor = new UsersListPresenter(this, mUserModel);
mActionInteractor.loadUsersList(false);
}
Scopes
 Determinam a intenção de duração de ciclo de vida de um
component;
 @Singleton é o único suportado out-of-the-box;
 Deve ser usado no nível de aplicação
 Custom scopes permitem maior flexibilidade, mas cabe
ao programador respeitar o ciclo de vida.
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerActivity {}
@Module
public class MyActivityModule {
@PerActivity
@Named("ActivityScope") @Provides
StringBuilder provideStringBuilderActivityScope() {
return new StringBuilder("Activity");
}
@Named("Unscoped") @Provides
StringBuilder provideStringBuilderUnscoped() {
return new StringBuilder("Unscoped");
}
}
public class MyActivity {
@Inject @Named("ActivityScope")
StringBuilder activityScope1;
@Inject @Named("ActivityScope")
StringBuilder activityScope2;
@Inject @Named("Unscoped")
StringBuilder unscoped1;
@Inject @Named("Unscoped")
StringBuilder unscoped2;
public void onCreate() {
activityScope1.append("123");
activityScope1.toString(); // output: "Activity123"
activityScope2.append("456");
activityScope2.toString(); // output: "Activity123456"
unscoped1.append("123");
unscoped1.toString(); // output: "Unscoped123"
unscoped2.append("456");
unscoped2.toString(); // output: "Unscoped456"
}
}
Bonus
 Lazy;
 Inicialização de Map e Set;
 Producer assíncrono;
Conclusão
 Fácil acesso à variáveis compartilhadas;
 Desacoplamento de dependências complexas;
 Controle de ciclo de vida;
 Performance.
Dúvidas?
edson-menegatti-87898718
3dm1
edson.menegatti.7
Referências
https://www.youtube.com/watch?v=oK_XtfXPkqw
https://github.com/codepath/android_guides/wiki/Dependenc
y-Injection-with-Dagger-2
https://www.parleys.com/tutorial/5471cdd1e4b065ebcfa1d55
7/
https://blog.gouline.net/2015/05/04/dagger-2-even-sharper-
less-square/
https://www.youtube.com/watch?v=SKFB8u0-VA0

More Related Content

What's hot

My way to clean android v2 English DroidCon Spain
My way to clean android v2 English DroidCon SpainMy way to clean android v2 English DroidCon Spain
My way to clean android v2 English DroidCon Spain
Christian Panadero
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
Ali Parmaksiz
 
My way to clean android V2
My way to clean android V2My way to clean android V2
My way to clean android V2
Christian Panadero
 
Open sourcing the store
Open sourcing the storeOpen sourcing the store
Open sourcing the store
Mike Nakhimovich
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalDroidcon Berlin
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
ICS
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
Tomáš Kypta
 
Android architecture blueprints overview
Android architecture blueprints overviewAndroid architecture blueprints overview
Android architecture blueprints overview
Chih-Chung Lee
 
Dagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionDagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency Injection
Stfalcon Meetups
 
Dagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency InjectionsDagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency Injections
GlobalLogic Ukraine
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
Pierre-Yves Ricau
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
Fabio Collini
 
Under the Hood: Using Spring in Grails
Under the Hood: Using Spring in GrailsUnder the Hood: Using Spring in Grails
Under the Hood: Using Spring in Grails
Burt Beckwith
 
Under the Hood: Using Spring in Grails
Under the Hood: Using Spring in GrailsUnder the Hood: Using Spring in Grails
Under the Hood: Using Spring in Grails
GR8Conf
 
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroid【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
Hiroyuki Kusu
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
GDG Korea
 
Android application model
Android application modelAndroid application model
Android application modelmagicshui
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJava
Fabio Collini
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
ICS
 
Automated%20testing%20with%20Espresso2.x
Automated%20testing%20with%20Espresso2.xAutomated%20testing%20with%20Espresso2.x
Automated%20testing%20with%20Espresso2.xTatsuya Maki
 

What's hot (20)

My way to clean android v2 English DroidCon Spain
My way to clean android v2 English DroidCon SpainMy way to clean android v2 English DroidCon Spain
My way to clean android v2 English DroidCon Spain
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
 
My way to clean android V2
My way to clean android V2My way to clean android V2
My way to clean android V2
 
Open sourcing the store
Open sourcing the storeOpen sourcing the store
Open sourcing the store
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-final
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Android architecture blueprints overview
Android architecture blueprints overviewAndroid architecture blueprints overview
Android architecture blueprints overview
 
Dagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionDagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency Injection
 
Dagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency InjectionsDagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency Injections
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Under the Hood: Using Spring in Grails
Under the Hood: Using Spring in GrailsUnder the Hood: Using Spring in Grails
Under the Hood: Using Spring in Grails
 
Under the Hood: Using Spring in Grails
Under the Hood: Using Spring in GrailsUnder the Hood: Using Spring in Grails
Under the Hood: Using Spring in Grails
 
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroid【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
 
Android application model
Android application modelAndroid application model
Android application model
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJava
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
 
Automated%20testing%20with%20Espresso2.x
Automated%20testing%20with%20Espresso2.xAutomated%20testing%20with%20Espresso2.x
Automated%20testing%20with%20Espresso2.x
 

Viewers also liked

Umbraco Introduction
Umbraco IntroductionUmbraco Introduction
Umbraco Introduction
Aliencube Consulting
 
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
GBC Finland
 
5126 5130.output
5126 5130.output5126 5130.output
5126 5130.output
j1075017
 
Andef manual boas_praticas_agricolas_web_081013192330
Andef manual boas_praticas_agricolas_web_081013192330Andef manual boas_praticas_agricolas_web_081013192330
Andef manual boas_praticas_agricolas_web_081013192330
Edwardi Steidle Neto
 
5141 5145.output
5141 5145.output5141 5145.output
5141 5145.output
j1075017
 
About Shared Value Initiative India
About Shared Value Initiative IndiaAbout Shared Value Initiative India
About Shared Value Initiative India
Dr. Amit Kapoor
 
Multiple sclerosis
Multiple sclerosisMultiple sclerosis
Multiple sclerosis
mandira dahal
 
Trabalho de fundamentos e metod. lingua portuguesa
Trabalho de fundamentos e metod. lingua portuguesaTrabalho de fundamentos e metod. lingua portuguesa
Trabalho de fundamentos e metod. lingua portuguesa
GilvaniaFernandesRibeiro
 
Dagger 2
Dagger 2Dagger 2
Dagger 2
Kirill Rozov
 
BREEAM and Environmental Assessment Methods Amanda Gallagher EASLAR
BREEAM  and Environmental Assessment Methods Amanda Gallagher EASLARBREEAM  and Environmental Assessment Methods Amanda Gallagher EASLAR
BREEAM and Environmental Assessment Methods Amanda Gallagher EASLAR
Ren Net
 

Viewers also liked (11)

Umbraco Introduction
Umbraco IntroductionUmbraco Introduction
Umbraco Introduction
 
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
 
5126 5130.output
5126 5130.output5126 5130.output
5126 5130.output
 
Andef manual boas_praticas_agricolas_web_081013192330
Andef manual boas_praticas_agricolas_web_081013192330Andef manual boas_praticas_agricolas_web_081013192330
Andef manual boas_praticas_agricolas_web_081013192330
 
5141 5145.output
5141 5145.output5141 5145.output
5141 5145.output
 
geo 202 shale gas
geo 202 shale gasgeo 202 shale gas
geo 202 shale gas
 
About Shared Value Initiative India
About Shared Value Initiative IndiaAbout Shared Value Initiative India
About Shared Value Initiative India
 
Multiple sclerosis
Multiple sclerosisMultiple sclerosis
Multiple sclerosis
 
Trabalho de fundamentos e metod. lingua portuguesa
Trabalho de fundamentos e metod. lingua portuguesaTrabalho de fundamentos e metod. lingua portuguesa
Trabalho de fundamentos e metod. lingua portuguesa
 
Dagger 2
Dagger 2Dagger 2
Dagger 2
 
BREEAM and Environmental Assessment Methods Amanda Gallagher EASLAR
BREEAM  and Environmental Assessment Methods Amanda Gallagher EASLARBREEAM  and Environmental Assessment Methods Amanda Gallagher EASLAR
BREEAM and Environmental Assessment Methods Amanda Gallagher EASLAR
 

Similar to Dagger 2 - Injeção de Dependência

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejugrobbiev
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
Javad Hashemi
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
go_oh
 
Android architecture
Android architecture Android architecture
Android architecture
Trong-An Bui
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
rhemsolutions
 
Android Bootstrap
Android BootstrapAndroid Bootstrap
Android Bootstrap
donnfelker
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatissimonetripodi
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
Schalk Cronjé
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
Ignacio Coloma
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
Pavel Lahoda
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon Berlin
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
VMware Tanzu
 
Android getting started
Android getting startedAndroid getting started
Android getting started
Uptech
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
Visual Engineering
 
Dependency injection crash course
Dependency injection crash courseDependency injection crash course
Dependency injection crash course
Robin Sfez
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript Dhananjay Kumar
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptor
Caelum
 

Similar to Dagger 2 - Injeção de Dependência (20)

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Android architecture
Android architecture Android architecture
Android architecture
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
Android Bootstrap
Android BootstrapAndroid Bootstrap
Android Bootstrap
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatis
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
Android getting started
Android getting startedAndroid getting started
Android getting started
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Dependency injection crash course
Dependency injection crash courseDependency injection crash course
Dependency injection crash course
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptor
 
droidparts
droidpartsdroidparts
droidparts
 

Recently uploaded

OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
abdulrafaychaudhry
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
QuickwayInfoSystems3
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
Google
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 

Recently uploaded (20)

OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 

Dagger 2 - Injeção de Dependência

  • 1. Dagger 2 INJEÇÃO DE DEPENDÊNCIA
  • 2. Injecão de Dependência  Dependência é qualquer objeto necessário para o funcionamento de uma classe;  Desacoplamento entre classes de alto e baixo nível;  Inexistente, manual ou automática.
  • 3. public class ClassA { private ClassB mClassB; public ClassA() { mClassB = new ClassB(); } }
  • 4. public class ClassA { private ClassB mClassB; public ClassA() { mClassB = new ClassB(new ClassC()); } }
  • 5. public class ClassA { private ClassB mClassB; public ClassA(ClassB classB) { mClassB = classB; } }
  • 6. Bibliotecas  Guice  Dagger (v1)  Dagger 2  ...
  • 7. Funcionamento @Bind(R.id.home_iv) ImageView mImageView; ButterKnife.bind(this, view); view mImageView findViewbyId @Bind mImageView = (ImageView)view.findViewbyId(R.id.home_iv);
  • 10. Retrofit Service public class GitHubApi { public static final int CACHE_SIZE = 5 * 1024 * 1024; public static <S> S createService(Class<S> serviceClass, Context context) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); final Gson gson = gsonBuilder.create(); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor) .cache(new Cache(context.getCacheDir(), CACHE_SIZE)) .readTimeout(30, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS) .build(); Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(BuildConfig.API_URL) .client(client) .build(); return retrofit.create(serviceClass); } }
  • 11. UserModel public class GitHubUserModel { private final GitHubService mService; public GitHubUserModel(Context context) { mService = GitHubApi.createService(GitHubService.class, context); } public Call<List<GitHubUser>> fetchUsers(int page) { return mService.getUsers(page); } ... } GitHubUserModel userModel = new GitHubUserModel(getActivity().getApplicationContext()); mActionInteractor = new UsersListPresenter(this, userModel); mActionInteractor.loadUsersList(false);
  • 13. Dagger API  @Module + @Provides  Mecanismo para prover dependências  @Inject  Mecanismo para requisitar dependências  @Component  Ligação entre módulos e injeções
  • 14. Dagger Project/build.gradle buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.5.0' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8’ } } App/build.gradle apply plugin: 'com.neenbedankt.android-apt' compile 'com.google.dagger:dagger:2.0.2' apt 'com.google.dagger:dagger-compiler:2.0.2' provided 'org.glassfish:javax.annotation:10.0-b28'
  • 15. @Module public class NetworkModule { public static final int CACHE_SIZE = 5 * 1024 * 1024; @Provides public Retrofit provideRetrofit(Gson gson, OkHttpClient client) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(BuildConfig.API_URL) .client(client) .build(); } @Provides public OkHttpClient provideHttpClient(HttpLoggingInterceptor interceptor, Cache cache) { return new OkHttpClient.Builder() .addInterceptor(interceptor) .cache(cache) .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .build(); } @Provides public Cache provideCache(Application application) { return new Cache(application.getCacheDir(), CACHE_SIZE); } @Provides public HttpLoggingInterceptor provideHttpInterceptor() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return interceptor; } @Provides public Gson provideHttpGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create(); } }
  • 16. @Module public class GitHubModule { public interface GitHubService { @GET("/users") @Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN) Call<List<GitHubUser>> getUsers(); @GET("/users/{login}") @Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN) Call<GitHubUser> getUser(@Path("login") String login); @GET("/users") @Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN) Call<List<GitHubUser>> getUsers(@Query("since") int page); } @Provides public GitHubService provideGitHubService(Retrofit retrofit) { return retrofit.create(GitHubService.class); } }
  • 17. @Module public class AppModule { private final Context mApplicationContext; public AppModule(Context applicationContext) { mApplicationContext = applicationContext; } @Provides @PerApp public Context provideApplicationContext() { return mApplicationContext; } }
  • 18. @Component(modules = {AppModule.class, GitHubModule.class, NetworkModule.class}) public interface AppComponent { void inject(UsersListFragment fragment); } DepencyInjectionApplication.java @NonNull protected DaggerAppComponent.Builder prepareAppComponent() { return DaggerAppComponent.builder() .networkModule(new NetworkModule()) .gitHubModule(new GitHubModule()) .appModule(new AppModule(this)); }
  • 19. GitHubUserModel.java public class GitHubUserModel { private final GitHubModule.GitHubService mService; @Inject public GitHubUserModel(GitHubModule.GitHubService service) { mService = service; } ... } UsersListFragment.java @Inject public GitHubUserModel mUserModel; @Override protected void onCreate() { DepencyInjectionApplication.getAppComponent(getActivity()).inject(this); } @Override protected void onResume() { mActionInteractor = new UsersListPresenter(this, mUserModel); mActionInteractor.loadUsersList(false); }
  • 22. @Component(modules={AppModule.class, NetworkModule.class}) public interface NetComponent { Retrofit retrofit(); } @Component(dependencies = NetComponent.class, modules = GitHubModule.class) public interface AppComponent { void inject(UsersListFragment fragment); } public class DepencyInjectionApplication extends Application { private AppComponent mAppComponent; private NetComponent mNetComponent; private void setupDaggerAppComponent() { mNetComponent = DaggerNetComponent.builder() .appModule(new AppModule(this)) // .networkModule(new NetworkModule()) is free .build(); mAppComponent = DaggerAppComponent.builder() // .gitHubModule(new GitHubModule()) is free .netComponent(mNetComponent) .build(); } }
  • 24. @Subcomponent(modules = GitHubModule.class) public interface GitHubComponent { void inject(UsersListFragment fragment); } @Component(modules = {NetworkModule.class, AppModule.class}) public interface AppComponent { Application getApplication(); GitHubComponent plus(GitHubModule gitHubModule); } DepencyInjectionApplication.java private void setupDaggerAppComponent() { mAppComponent = DaggerAppComponent.builder() .appModule(new AppModule(this)) .build(); } UsersListFragment.java @Override protected void onCreate() { DepencyInjectionApplication.getAppComponent(getActivity()) .plus(new GitHubModule()) .inject(this); } @Override protected void onResume() { mActionInteractor = new UsersListPresenter(this, mUserModel); mActionInteractor.loadUsersList(false); }
  • 25. Scopes  Determinam a intenção de duração de ciclo de vida de um component;  @Singleton é o único suportado out-of-the-box;  Deve ser usado no nível de aplicação  Custom scopes permitem maior flexibilidade, mas cabe ao programador respeitar o ciclo de vida.
  • 26. @Scope @Retention(RetentionPolicy.RUNTIME) public @interface PerActivity {} @Module public class MyActivityModule { @PerActivity @Named("ActivityScope") @Provides StringBuilder provideStringBuilderActivityScope() { return new StringBuilder("Activity"); } @Named("Unscoped") @Provides StringBuilder provideStringBuilderUnscoped() { return new StringBuilder("Unscoped"); } }
  • 27. public class MyActivity { @Inject @Named("ActivityScope") StringBuilder activityScope1; @Inject @Named("ActivityScope") StringBuilder activityScope2; @Inject @Named("Unscoped") StringBuilder unscoped1; @Inject @Named("Unscoped") StringBuilder unscoped2; public void onCreate() { activityScope1.append("123"); activityScope1.toString(); // output: "Activity123" activityScope2.append("456"); activityScope2.toString(); // output: "Activity123456" unscoped1.append("123"); unscoped1.toString(); // output: "Unscoped123" unscoped2.append("456"); unscoped2.toString(); // output: "Unscoped456" } }
  • 28. Bonus  Lazy;  Inicialização de Map e Set;  Producer assíncrono;
  • 29. Conclusão  Fácil acesso à variáveis compartilhadas;  Desacoplamento de dependências complexas;  Controle de ciclo de vida;  Performance.