Guice2.0
‐New Features and 3rd Party Modules‐


                     Jul 15th, 2009
introduction
Name
   Masaaki Yonebayashi
ID
  id:yone098
Blog
  http://d.hatena.ne.jp/yone098/
Company
  Abby Co.,Ltd.  President
Agenda
Guice2.0 New Features
 Provider Methods
 Binding Override
 MultiBindings, MapBindings
 Private Modules

Tips
Third Party Modules
 Testing
 Other Language
Guice2.0




New Features
Guice2.0
Guice 2.0
 Released May 19, 2009
URL
 http://code.google.com/p/google‐guice/
guice‐2.0‐no_aop.jar
 For Android(not support AOP)
Wiki
 http://code.google.com/p/google‐guice/wiki/Guice20
New Features




Provider Methods
Provider Methods
     example          public interface Pet {
                        void run();
                      }

public class Cat implements Pet {    public class Dog implements Pet {
  private String name;                 private String name;
  public Cat(String name) {            public Dog(String name) {
    this.name = name;                    this.name = name;
  }                                    }
  public void run() {                  public void run() {
   System.out.println(                  System.out.println(
     name + “ Cat is run");               name + “ Dog is run");
 }                                     }
}                                    }
Provider Methods
    Guice1.0
Injector injector = Guice.createInjector(new AbstractModule() {
  @Override
  public void configure() {
    bind(Pet.class).toProvider(new Provider<Pet>() {
      public Pet get() {
        return new Dog("new Provider<Pet>");
      }
    }).in(Singleton.class);
  }
});
Pet pet = injector.getInstance(Pet.class);
pet.run();
Provider Methods
    Guice1.0
Injector injector = Guice.createInjector(new AbstractModule() {
  @Override
  public void configure() {
    bind(Pet.class).toProvider(new Provider<Pet>() {
      public Pet get() {
   new Provider<Pet> Dog is run
        return new Dog("new Provider<Pet>");
      }
    }).in(Singleton.class);
  }
});
Pet pet = injector.getInstance(Pet.class);
pet.run();
Provider Methods
    Guice2.0
Injector injector = Guice.createInjector(new AbstractModule() {
  @Override
  public void configure() {
  }
  @Provides @Singleton
  Pet providePet() {
    return new Cat("@Provides");
  }
});
Pet pet = injector.getInstance(Pet.class);
pet.run();
Provider Methods
    Guice2.0
Injector injector = Guice.createInjector(new AbstractModule() {
  @Override
  public void configure() {
  }
  @Provides @Singleton
   @Provides Cat is run
  Pet providePet() {
    return new Cat("@Provides");
  }
});
Pet pet = injector.getInstance(Pet.class);
pet.run();
Question
    Guice2.0
Injector injector = Guice.createInjector(new AbstractModule() {
  @Override
  public void configure() {
  }
  @Provides @Singleton
  Pet providePet() {
    return new Cat("@Provides");
  }
  @Provides @Singleton
  Pet providePet2() {
    return new Cat("@Provides2");
  }
});
Provider Methods
   CreationException :(
Exception in thread "main" 
  com.google.inject.CreationException: Guice creation 
  errors:

1) A binding to samples.providermethod.Pet was already 
  configured at 
  samples.providermethod.ProviderMethods$1.providePet().
  at 
  samples.providermethod.ProviderMethods$1.providePet2(P
  roviderMethods.java:33)
Provider Methods
   CreationException :(
Exception in thread "main" 
  com.google.inject.CreationException: Guice creation 
  errors:

1) A binding to samples.providermethod.Pet was already 
  configured at 
  samples.providermethod.ProviderMethods$1.providePet().
  at 
  samples.providermethod.ProviderMethods$1.providePet2(P
  roviderMethods.java:33)


                                          demo
Provider Methods




solves it
solved it
    Provides with Named
Injector injector = Guice.createInjector(new AbstractModule() {
  @Override
  public void configure() {
  }
  @Provides @Singleton
  Pet providePet() {
    return new Cat("@Provides");
  }
  @Provides @Singleton @Named(“NYAAA”)
  Pet providePet2() {
    return new Cat("@Provides2");
  }
});
solved it
   named
import static
  com.google.inject.name.Names.named;
Pet pet = injector.getInstance(Pet.class);
pet.run();

Pet nyaaa = injector.getInstance(
    Key.get(Pet.class, named("NYAAA")));
nyaaa.run();
solved it
   named
import static
  com.google.inject.name.Names.named;
Pet pet = injector.getInstance(Pet.class);
pet.run();
  @Provides Cat is run
  @Provedes2 Cat is run
Pet nyaaa = injector.getInstance(
    Key.get(Pet.class, named("NYAAA")));
nyaaa.run();
Question
   void Provider Methods
Injector injector = Guice.createInjector(new
  AbstractModule() {
  @Override
  public void configure() {
  }
  @Provides
  void sample() {
  }
});
Provider Methods
   CreationException :(
Exception in thread "main" 
  com.google.inject.CreationException: Guice 
  creation errors:

1) Provider methods must return a value. Do not 
  return void.
  at 
  samples.providermethod.ProviderMethods$1.sample(P
  roviderMethods.java:40)
Provider Methods
   CreationException :(
Exception in thread "main" 
  com.google.inject.CreationException: Guice 
  creation errors:

1) Provider methods must return a value. Do not 
  return void.
  at 
  samples.providermethod.ProviderMethods$1.sample(P
  roviderMethods.java:40)


                                       demo
New Features



Provider Methods Summary
Provider Methods summary


The definition is simple.
There is no generation cost of the 
Provider class.
It is a short cut.
New Features




Binding Overrides
Binding Overrides
   Sample Module
private static Module module1() {
  return new AbstractModule() {
     protected void configure() {
       bind(Pet.class).to(Dog.class);
    }
  };
}
Binding Overrides
   Module override
Injector injector = createInjector(
  Modules.override(module1())
    .with(new AbstractModule() {
      protected void configure() {
        bind(Pet.class).to(Cat.class);
      }
    }
));
Pet pet = injector.getInstance(Pet.class);
pet.run();
Binding Overrides
   Module override
Injector injector = createInjector(
  Modules.override(module1())
    .with(new AbstractModule() {
      protected void configure() {
   Cat is run
        bind(Pet.class).to(Cat.class);
      }
    }
));
Pet pet = injector.getInstance(Pet.class);
pet.run();
New Features



Binding Overrides
Override multiple
Binding Overrides
    override multiple
private static <T> Module newModule(final T bound) {
  return new AbstractModule() {
     protected void configure() {
       @SuppressWarnings("unchecked")
       Class<T> type = (Class<T>) bound.getClass();
       bind(type).toInstance(bound);
     }
  };
}
Binding Overrides
  override multiple
Module module = Modules.override(
   newModule("A"), 
   newModule(1),
   newModule(0.5f)
).with(
   newModule("B"), 
   newModule(2),
   newModule(1.5d)
);
Injector injector = createInjector(module);
Binding Overrides
 override multiple
assertEquals("B", 
    injector.getInstance(String.class));
assertEquals(0.5f, 
    injector.getInstance(Float.class));
assertEquals(1.5d, 
    injector.getInstance(Double.class));
New Features



Binding Overrides
Override constant
Binding Overrides
  override constant
Module original = new AbstractModule() {
  protected void configure() {
     bindConstant().annotatedWith(named(“c9")).to(“ak");
  }
};
Module replacements = new AbstractModule() {
   protected void configure() {
     bindConstant().annotatedWith(named(“c9")).to(“yaman");
   }
};
Injector injector = 
   createInjector(Modules.override(original)
                  .with(replacements));
Binding Overrides
 override constant
Injector injector = 
 createInjector(Modules.override(original)
      .with(replacements));

assertEquals("yaman",
  injector.getInstance(
    Key.get(String.class, named("c9"))));
Binding Override summary


An existing module can be recycled.
The offered module can be 
customized.
New Features



 MultiBindings,
MapBindings
Guice2.0

dependency
 guice‐multibindings‐2.0.jar
 artifactId
  multibindings
 groupId
  com.google.inject.extension
New Features




MultiBindings
MultiBindings
  MultiBindings
Module abc = new AbstractModule() {
   protected void configure() {
     Multibinder<String> multibinder =
       Multibinder.newSetBinder(
           binder(), String.class);
     multibinder.addBinding().toInstance("A");
     multibinder.addBinding().toInstance("B");
     multibinder.addBinding().toInstance("C");
   }
};
MultiBindings
  MultiBindings
Injector injector = Guice.createInjector(abc);
Set<String> abcStr = 
  injector.getInstance(Key.get(
    new TypeLiteral<Set<String>>() {}
  ));

assertEquals(setOf("A", "B", "C"), abcStr);
MultiBindings
  MultiBindings
private static class Test {
  @Inject
  private Set<String> multiString;
}

Test test = injector.getInstance(Test.class);
assertEquals(setOf("A", "B", "C"), 
  test.multiString);
New Features




MapBindings
MapBindings
  MapBindings
Module abc = new AbstractModule() {
   protected void configure() {
     MapBinder<String, String> multibinder =     
     MapBinder.newMapBinder(
       binder(), String.class, String.class);
     multibinder.addBinding("a").toInstance("A");
     multibinder.addBinding("b").toInstance("B");
     multibinder.addBinding("c").toInstance("C");
   }
};
MapBindings
  MapBindings
Injector injector = Guice.createInjector(abc);
Map<String, String> abcMap = 
  injector.getInstance(Key.get(
    new TypeLiteral<Map<String, String>>(){}
  ));

assertEquals(
   mapOf("a", "A", "b", "B", "c", "C"),
   abcMap
);
MapBindings
  MapBindings
private static class Test {
  @Inject
  private Map<String, String> map;
}

Test test = injector.getInstance(Test.class);
assertEquals(
   mapOf("a", "A", "b", "B", "c", "C"), 
   test.map
);
New Features



MapBindings
•with AnnotationType
MapBindings
 MapBindings with AnnotationType
/**
 * Ikemen annotation
 */
@Retention(RUNTIME)
@BindingAnnotation
@interface C9 {
}
MapBindings
  MapBindings with AnnotationType
Injector injector = Guice.createInjector(
  new AbstractModule() {
  protected void configure() {
    MapBinder<String, Integer> mapBinder = MapBinder
    .newMapBinder(binder(), 
        String.class, Integer.class, C9.class);
    mapBinder.addBinding("yaman").toInstance(35);
    mapBinder.addBinding("shot6").toInstance(31);
    mapBinder.addBinding("yone098").toInstance(31);
    mapBinder.addBinding("skirnir").toInstance(52);
  }
});
MapBindings
  MapBindings with AnnotationType
Map<String, Integer> abc = 
  injector.getInstance(Key.get(
    new TypeLiteral<Map<String, Integer>>(){},
    C9.class));

assertEquals(
  mapOf("yaman", 35, "shot6", 31, 
    "yone098", 31, "skirnir", 52), 
  abc
);
MapBindings
  MapBindings with AnnotationType
private static class Ikemen {
  @Inject
  @C9
  Map<String, Integer> map;
}

Ikemen ikemen = injector.getInstance(Ikemen.class);
assertEquals(
  mapOf("yaman", 35, "shot6", 31, 
        "yone098", 31, "skirnir", 52), 
  ikemen.map);
MultiBindings summary


The advantage of MultiBindings is 
not found. :(
It depends on guice‐multibindings‐
2.0.jar.
New Features




PrivateModule
PrivateModule
  PrivateModule
Injector injector = Guice.createInjector(
  new PrivateModule() {
  public void configure() {
    bind(String.class).annotatedWith(named("c9"))
     .toInstance("katayama");
     expose(String.class).annotatedWith(named("c9"));
  }
});
assertEquals("katayama",
  injector.getInstance(Key.get(String.class,
    named("c9"))));
PrivateModule
  PrivateModule
private static class Test {
@Inject
@Named("c9")
private String c9katayama;
}

Test test = injector.getInstance(Test.class);
assertEquals("katayama", test.c9katayama);
New Features



PrivateModule
expose
PrivateModule
  PrivateModule
Injector injector = Guice.createInjector(
  new PrivateModule() {
  public void configure() {
    bind(String.class).annotatedWith(named("c9"))
     .toInstance("katayama");
     expose(String.class).annotatedWith(named("c9"));
  }
});
assertEquals("katayama",
  injector.getInstance(Key.get(String.class,
    named("c9"))));
PrivateModule
  PrivateModule
Injector injector = Guice.createInjector(
  new PrivateModule() {
  public void configure() {
    bind(String.class).annotatedWith(named("c9"))
     .toInstance("katayama");
     expose(String.class).annotatedWith(named("c9"));
  }
});
assertEquals("katayama",
  injector.getInstance(Key.get(String.class,
    named("c9"))));

                                         demo
New Features



PrivateModule
@Exposed
PrivateModule
    PrivateModule
Injector injector = Guice.createInjector(
  new PrivateModule(){
    protected void configure() { }
    @Provides @Named("c9") @Exposed 
    String provideKata() { return "KATA"; }
  }, new AbstractModule() {
    protected void configure() { }
    @Provides @Named("yaman")
    String provideYama(@Named("c9") String c9) {
      return c9 + "YAMA";
    }
});
PrivateModule
  PrivateModule
assertEquals("KATAYAMA", 
  injector.getInstance(Key.get(
    String.class,
    named("yaman")))
);




                                  demo
PrivateModule


Use it positively if you make the 
framework.
It will become easy to design the 
module.
The module can be safely used by 
limiting scope.
Guice2.0
New Features




InjectionListener



                demo
New Features




Names.bindProperties




                 demo
Guice2.0



Third Party Modules
Third Party Modules




Testing
Third Party Modules
GuiceBerry
 JUnit and integration testing
 http://code.google.com/p/guiceberry/
AtUnit
 JUnit and mocking frameworks (JMock, 
 EasyMock)
 http://code.google.com/p/atunit/
Third Party Modules




Other Language
Third Party Modules
Groovy‐Guice(Groovy)
 http://code.google.com/p/groovy‐guice/
Ninject(.NET)
 http://ninject.org/
Snake Guice(Python)
 http://code.google.com/p/snake‐guice/
Smartypants‐IOC(Flex)
 http://code.google.com/p/smartypants‐
 ioc/
Guice2.0




Summary
summary



Enjoy! Guice2.0
Haiku


Today
very hot
No Haiku❤
Thank you!
    :)

More Related Content

PDF
guice-servlet
PDF
Easy REST APIs with Jersey and RestyGWT
PDF
Grid gain paper
PPTX
The uniform interface is 42
ODP
Jersey Guice AOP
PPTX
Junit 5 - Maior e melhor
PDF
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
DOCX
Ejemplo radio
guice-servlet
Easy REST APIs with Jersey and RestyGWT
Grid gain paper
The uniform interface is 42
Jersey Guice AOP
Junit 5 - Maior e melhor
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
Ejemplo radio

What's hot (20)

PDF
Clustering your Application with Hazelcast
PDF
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
PDF
Kotlin Generation
DOC
Converting Db Schema Into Uml Classes
PPTX
Data binding в массы! (1.2)
PPTX
Writing and using Hamcrest Matchers
PDF
The Ring programming language version 1.5.2 book - Part 76 of 181
KEY
That’s My App - Running in Your Background - Draining Your Battery
PDF
Mobile Fest 2018. Александр Корин. Болеутоляющее
PDF
What Have The Properties Ever Done For Us
PDF
Vavr Java User Group Rheinland
PDF
Java libraries you can't afford to miss
PDF
yagdao-0.3.1 JPA guide
PDF
Dependency Injection with CDI in 15 minutes
PPTX
Unit/Integration Testing using Spock
PDF
京都Gtugコンパチapi
PDF
Why Kotlin - Apalon Kotlin Sprint Part 1
PDF
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
PPTX
разработка серверов и серверных приложений лекция №4
PDF
Vielseitiges In-Memory Computing mit Apache Ignite und Kubernetes
Clustering your Application with Hazelcast
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
Kotlin Generation
Converting Db Schema Into Uml Classes
Data binding в массы! (1.2)
Writing and using Hamcrest Matchers
The Ring programming language version 1.5.2 book - Part 76 of 181
That’s My App - Running in Your Background - Draining Your Battery
Mobile Fest 2018. Александр Корин. Болеутоляющее
What Have The Properties Ever Done For Us
Vavr Java User Group Rheinland
Java libraries you can't afford to miss
yagdao-0.3.1 JPA guide
Dependency Injection with CDI in 15 minutes
Unit/Integration Testing using Spock
京都Gtugコンパチapi
Why Kotlin - Apalon Kotlin Sprint Part 1
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
разработка серверов и серверных приложений лекция №4
Vielseitiges In-Memory Computing mit Apache Ignite und Kubernetes
Ad

Viewers also liked (9)

PDF
Dena Loves Perl
PDF
ALA Member Benefits Guide
PDF
Megrisoft Corporate Fact Sheet
PPT
Ala Fall PD Day Presentation v2
PPT
Ala Fall PD Day Presentation
PDF
Cultivating Campus Collaborations
PPT
Savy Training 16.05.2009
PDF
Cognotes - Sunday June 26
PDF
A list of companies
Dena Loves Perl
ALA Member Benefits Guide
Megrisoft Corporate Fact Sheet
Ala Fall PD Day Presentation v2
Ala Fall PD Day Presentation
Cultivating Campus Collaborations
Savy Training 16.05.2009
Cognotes - Sunday June 26
A list of companies
Ad

Similar to Guice2.0 (20)

PPTX
Dependency Injection for Android
PPTX
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
DOCX
VISUALIZAR REGISTROS EN UN JTABLE
PPT
Unit testing with mock libs
PDF
Architecting your GWT applications with GWT-Platform - Lesson 02
PDF
Jug Guice Presentation
PPTX
Secret unit testing tools no one ever told you about
PPTX
Nice to meet Kotlin
PPT
Spring Boot Introduction and framework.ppt
PPTX
Sword fighting with Dagger GDG-NYC Jan 2016
PPTX
Java осень 2012 лекция 2
PDF
Sharper Better Faster Dagger ‡ - Droidcon SF
PDF
Devoxx 2012 (v2)
PDF
Testing in android
PDF
JJUG CCC 2011 Spring
PDF
Alexey Buzdin "Maslow's Pyramid of Android Testing"
PDF
Object Oriented Solved Practice Programs C++ Exams
ZIP
とある断片の超動的言語
PDF
The Ring programming language version 1.4.1 book - Part 16 of 31
PDF
Daggerate your code - Write your own annotation processor
Dependency Injection for Android
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
VISUALIZAR REGISTROS EN UN JTABLE
Unit testing with mock libs
Architecting your GWT applications with GWT-Platform - Lesson 02
Jug Guice Presentation
Secret unit testing tools no one ever told you about
Nice to meet Kotlin
Spring Boot Introduction and framework.ppt
Sword fighting with Dagger GDG-NYC Jan 2016
Java осень 2012 лекция 2
Sharper Better Faster Dagger ‡ - Droidcon SF
Devoxx 2012 (v2)
Testing in android
JJUG CCC 2011 Spring
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Object Oriented Solved Practice Programs C++ Exams
とある断片の超動的言語
The Ring programming language version 1.4.1 book - Part 16 of 31
Daggerate your code - Write your own annotation processor

More from Masaaki Yonebayashi (14)

PPTX
Go guide for Java programmer
PDF
PDF
Android T2 on cloud
PDF
JavaFX-with-Adobe
PDF
Flex's DI Container
PDF
T2 in Action
PDF
T2@java-ja#toyama
PDF
Merapi -Adobe Air<=>Java-
PDF
sc2009white_T2
PDF
sc2009white_Teeda
PDF
Wankumatoyama#01
Go guide for Java programmer
Android T2 on cloud
JavaFX-with-Adobe
Flex's DI Container
T2 in Action
T2@java-ja#toyama
Merapi -Adobe Air<=>Java-
sc2009white_T2
sc2009white_Teeda
Wankumatoyama#01

Recently uploaded (20)

PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PPTX
Chapter 5: Probability Theory and Statistics
PDF
Enhancing plagiarism detection using data pre-processing and machine learning...
PPT
What is a Computer? Input Devices /output devices
PDF
Convolutional neural network based encoder-decoder for efficient real-time ob...
PDF
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
PDF
Getting started with AI Agents and Multi-Agent Systems
PPT
Module 1.ppt Iot fundamentals and Architecture
PPT
Galois Field Theory of Risk: A Perspective, Protocol, and Mathematical Backgr...
PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
Improvisation in detection of pomegranate leaf disease using transfer learni...
PDF
OpenACC and Open Hackathons Monthly Highlights July 2025
PPTX
TEXTILE technology diploma scope and career opportunities
PPTX
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
PPTX
Configure Apache Mutual Authentication
PPT
Geologic Time for studying geology for geologist
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
Flame analysis and combustion estimation using large language and vision assi...
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
The influence of sentiment analysis in enhancing early warning system model f...
Chapter 5: Probability Theory and Statistics
Enhancing plagiarism detection using data pre-processing and machine learning...
What is a Computer? Input Devices /output devices
Convolutional neural network based encoder-decoder for efficient real-time ob...
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
Getting started with AI Agents and Multi-Agent Systems
Module 1.ppt Iot fundamentals and Architecture
Galois Field Theory of Risk: A Perspective, Protocol, and Mathematical Backgr...
Custom Battery Pack Design Considerations for Performance and Safety
A review of recent deep learning applications in wood surface defect identifi...
Improvisation in detection of pomegranate leaf disease using transfer learni...
OpenACC and Open Hackathons Monthly Highlights July 2025
TEXTILE technology diploma scope and career opportunities
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
Configure Apache Mutual Authentication
Geologic Time for studying geology for geologist
Final SEM Unit 1 for mit wpu at pune .pptx
Flame analysis and combustion estimation using large language and vision assi...

Guice2.0