6. Download contents
Guice 1.0 Download contents
needs JDK for Java 5 or above
File description
guice‐1.0.jar The core Guice framework
guice‐servlet‐1.0.jar Web‐related scope addition
guice‐spring‐1.0.jar Binding Spring beans
guice‐struts2‐plugin‐ Plugin to use Guice as the
1.0.jar DI engine for Struts2
aopalliance.jar AOP Alliance API, needed to
use Guice AOP
9. Injection style
Guice Injection styles
Injection Locaion example
order
Constructor public class Ex {
1
@Inject
public Ex(AaService aaService){…}
}
@Inject
2 Field
private BbService bbService;
@Inject
3 Setter
public void setCcService(
CcService ccService){…}
10. Injection setting
Module(settings by Java)
class SampleModule extends AbstractModule {
@Override
protected void configure() {
bind(Service.class).to(ServiceImpl.class);
}
}
11. Injection setting
Module(settings by Java)
class SampleModule extends AbstractModule {
@Override
If you don’t set it
protected void configure() {
bind(Service.class).to(ServiceImpl.class);
}
}
12. Injection setting
ConfigurationException :(
com.google.inject.ConfigurationException:
Error at
samples.Client.<init>(Client.java:20)
Binding to samples.Service not found.
No bindings to that type were found.
13. Injection setting
ConfigurationException :(
com.google.inject.ConfigurationException:
Error at
samples.Client.<init>(Client.java:20)
Binding to samples.Service not found.
No bindings to that type were found.
demo
19. Question
Choosing Between Implementations
public interface Pet {
String name();
void run();
}
public class Cat implements Pet { public class Dog implements Pet {
public String name() { public String name() {
return quot;Catquot;; return “Dogquot;;
} }
public void run() { public void run() {
System.out.println(quot;Cat is runquot;); System.out.println(“Dog is runquot;);
} }
} }
21. Question
Choosing Between Implementations
Public static void main(String[] args) {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(Pet.class).to(Dog.class);
bind(Pet.class).to(Cat.class);
}
});
Person person = injector.getInstance(Person.class);
person.runWithPet();
}
22. Answer
CreationException :(
Exception in thread quot;mainquot;
com.google.inject.CreationException: Guice configuration
errors:
1) Error at
samples.GuicePetSample$1.configure(GuicePetSample.java:16
):
A binding to samples.Pet was already configured at
samples.GuicePetSample$1.configure(GuicePetSample.java:15
).
23. Answer
CreationException :(
Exception in thread quot;mainquot;
com.google.inject.CreationException: Guice configuration
errors:
1) Error at
samples.GuicePetSample$1.configure(GuicePetSample.java:16
):
A binding to samples.Pet was already configured at
samples.GuicePetSample$1.configure(GuicePetSample.java:15
).
demo