Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dagger 2 example

This example contains initially 3 java files:

  • SearchApp.java Has the main method
  • SearchInPage.java Perfoms the search of a keyword in a string
  • HttpClient.java Fetch a webpage

SearchInPage has a dependency on HttpClient, this example is to show how Dagger 2 can be used as Dependency Injection framework.

With Dagger 2 we change the dependency by adding the @Inject annotation, and we add 2 more clases: a Module and a Component which will be used by Dagger 2 to generate the required code to satisfy the dependency injection

package app;
import java.net.*;
import java.io.*;
public class HttpClient {
/**
* Fetch the given URI and returns a string with the content.
*/
public String doGet(String uri) {
try {
URL url = new URL(uri);
InputStream in = url.openConnection().getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream os = new ByteArrayOutputStream();
for( int len; ( len = in.read(buffer)) != -1 ;) {
os.write(buffer, 0 , len );
}
os.flush();
return new String(os.toByteArray());
} catch ( Exception e ) {
throw new RuntimeException(e);
}
}
}
package app;
public class SearchApp {
public static void main( String ... args ) {
SearchInPage a = DaggerSearchComponent.create().searchInPage();
for ( String s : a.search("domains") ) {
System.out.println(s);
}
}
}
package app;
import dagger.Component;
@Component( modules = SearchModule.class )
public interface SearchComponent {
SearchInPage searchInPage();
}
package app;
import java.util.*;
import javax.inject.Inject;
public class SearchInPage {
@Inject HttpClient client;
@Inject String host;
@Inject
public SearchInPage() {}
/**
* Search for the given keyword in the page
*/
public List<String> search( String keywork ) {
String content = client.doGet(host);
List<String> result = new ArrayList<String>();
StringBuilder wordBuffer = new StringBuilder();
// iterates the content
// and test if a word matches the keyword
// when a white space is found
for( int i = 0 ; i < content.length() ; i++ ) {
char c = content.charAt(i);
if (Character.isWhitespace(c) ) {
String word = wordBuffer.toString();
if ( word.equals(keywork) ) {
result.add(word);
}
wordBuffer.setLength(0);
} else {
wordBuffer.append(c);
}
}
return result;
}
}
package app;
import dagger.Module;
import dagger.Provides;
@Module
public class SearchModule {
@Provides HttpClient provideHttpClient() {
return new HttpClient();
}
@Provides String provideHost() {
return "http://www.iana.org/domains/reserved";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.