Google Guice 1.0
by wouter on Jan.06, 2009, under Uncategorized
Guice a lightweight dependency injection framework developed by Google. After using Spring all the time this is a different way of dependency injection but keep in mind that its still a lightweight framework so the support you get from Spring is somewhat bigger but Guice is at version 1.0 so the future will tell.
Modules:
Guice is based on modules, the modules are used to define what Guice has to inject. You can write a module by implementing the Module interface or by extending the AbstractModule class. The interface and the class define the implementation of the configure method. In this method you get a binder, this binder is used to instruct Guice on what to inject.
An example will tell more about how its done:
public class MyModule implements Module {
public void configure(Binder binder) {
binder.bind(Service.class)
.to(ServiceImpl.class)
.in(Scopes.SINGLETON);
}
}
The example shows the binding of the Service interface to the ServiceImpl class as a Singleton.
Guice will inject the same(singleton) instance of ServiceImpl class when you ask to inject the Service.
Injecting can be done very easily with the @Inject annotation and you can use this on constructors, fields and methods:
public class Client {
private final Service service;
@Inject
public Client(Service service) {
this.service = service;
}
public void go() {
service.go();
}
}
Instead of binding to a “.class” you can also bind to an instance:
// Bind Bar to an instance of Bar.
Bar bar = new Bar();
binder.bind(Bar.class).toInstance(bar);
Annotations:
Besides instructing the Guice framework by binding in a module you can also use annotations to instruct Guice.
The binding between the Service interface and the ServiceImpl class as in the first example can be done with the @ImplementedBy annotation:
@ImplementedBy(ServiceImpl.class)
public interface Service {
void go();
}
This doesn’t cover the singleton scope, to make the ServiceImpl class a singleton you have to annotate it with @Singleton:
@Singleton
public class ServiceImpl implements Service {
public void go() {
…
}
}
Startup:
The first stage of the Guice architecture is the startup, during the startup you create an injector that is used to inject into objects at runtime.
An example of a main method will explain more than words:
public class Main {
public static void main(String[] args) {
Injector injector = Guice.createInjector(Stage.PRODUCTION, new MyModule());
Client client = injector.getInstance(Client.class);
client.go();
}
}
In the example we create an injector by passing an instance of our module “MyModule” and the wanted Stage. Guice creates the binder and passes it to the module which contains the defined bindings. The Stage we specify is an extra attribute but very handy. There are two stages available, the Development and the Production stage. The difference is that in the development stage the singletons are instantiated on demand and in the production stage they are instantiated on startup.
Runtime:
Runtime is the second stage of the architecture, at this time we can use the injector created in the startup stage to inject objects. The injector consists of bindings. These bindings are represented by a key and the key consists of a type and an optional annotation. More on the optional annotation in the part about Annotation bindings.
Each binding has a provider which you can give a class and Guice will create an instance of that class.
Creating a new instance each time is the default for having no scope but each binding can have a custom scope that can decide if Guice needs to create a new instance or not. For example, you can create one instance per HttpSession:
binder.bindScope(SessionScoped.class, ServletScopes.SESSION);
If you need to bind multiple Service implementations to the Service interface you need to be able to differentiate the bindings. This can be done with annotations:
.annotatedWith(Blue.class)
.to(BlueService.class);
Here you see the bind being extended to check for the @Blue annotation:
@Inject
public void injectService(@Blue Service service) {
…
}
The @Blue annotation is custom annotation. Creating annotations that can be used in Guice requires you to use a guice annotation in your custom annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Blue {}
The @BindingAnnotation is the Guice specific annotation that indicates the usage of this annotation @Blue in Guice.
Annotation attributes:
If you already have enough differentiation with the basic annotation like @Blue you can skip this part. This part is about annotation attributes to add even more differentation to the injections. You can create your own annotation or you can use the @Named annotation provided by Guice in the com.google.inject.name package:
@Inject
public Client(@Named(“cars”) Service service) {
this.service = service;
}
The binding configured in the module:
@Override
protected void configure() {
bind(Service.class)
.annotatedWith(Names.named(“cars”))
.to(CarServiceImpl.class);
}
Implicit bindings:
Declaring bindings to concrete classes(not behind an interface) isn’t useful. You can declare them but it doesn’t make much sense:
If you need multiple instances of the same class then you can inject a provider for that class which enables you to call Provider<T>.get(); :@Inject
public void injectAtm(Provider<Money> atm) {
Money one = atm.get();
Money two = atm.get();
…
}It will happen that you need to create the objects because of 3rd party tools. This can be fixed by writing a custom provider for that class:
class WidgetProvider implements Provider<Widget> {
final Service service;
@Inject
WidgetProvider(Service service) {
this.service = service;
}
public Widget get() {
return new Widget(service);
}
}
The binding is done as follows:
bind(Widget.class).toProvider(WidgetProvider.class);
A great example on how to integrate with JNDI can be found in the Guice user guide.
Constant values:
Guice has a special treatment when injecting constant values:
- primitive types(int, char, …)
- primitive wrapper types(Integer, Double, …)
- Strings
- Enums
- Classes
bindConstant().annotatedWith(TheAnswer.class).to(42);
When binding Strings Guice will check for enums and classes by converting the String.
This can be handy when binding Strings from a properties file.Eagerly loading bindings:
To load an object at startup for initialization you need to declare them as eager singletons: bind(StartupTask.class).asEagerSingleton();
Injection between scopes(switching scopes):
This can be done in a safe manner, you can inject an HttpSession scoped object into an HttpRequest scoped object. Going from a bigger scope to a smaller one is no problem but the other way around is harder. This can be fixed by injecting a Provider<T> to retrieve the object.
Intercepting methods:
Just like in Spring you can write intercepting methods using AOP. An example is a Transaction interceptor that intercepts all methods with the @Transactional annotation:binder.bindInterceptor(
any(), // Match classes.
annotatedWith(Transactional.class), // Match methods.
new TransactionInterceptor() // The interceptor.
);
Optional injection:
Injection can be made optional for methods and fields, not constructors.
This is useful when there is no binding available then a default instance is used:
Last but not least I want to give you an example of a unit test using Guice:
public void setUp() throws Exception {
mockService = new MockService();
Module module = new AbstractModule() {
@Override
protected void configure() {
bind(Service.class).toInstance(mockService);
}
};
injector = Guice.createInjector(Stage.DEVELOPMENT, module);
}
public void testGo() {
Client client = injector.getInstance(Client.class);
client.go();
assertTrue(mockService.isGone());
}
Springsource dm server
by wouter on Nov.05, 2008, under Uncategorized
The Springsource dm(dynamic module) server is a module based Java application server that can be used for spring powered applications and Java enterprise applications. The reason im writing a blog post about this project is the use in combination with Sping dynamic modules.
The server is build up with Spring Framework, Tomcat(web container), OSGi R4.1, Equinox(OSGi impl.), Spring dynamic modules, SpringSource Tool Suite and Spring Application Management Suite.
For more information about Spring dynamic modules I refer to my previous blog post.
The server is at version 1.0.0 but it’s already a nice package to work with. The Documentation offers a user guide and a programming guide. The user guide helps you installing and configuring the server, the telnet console, the deployment timeout, the embedded tomcat server, linking the user bundles to an Ivy cache or a maven local repository, etc…
The programming guide is the one I liked the most, it helps you out step by step how to convert your web application to a web application with shared libraries at first and later on they explain how to work with shared services. If you have your libraries, services and web module as seperate bundles you can group them in a .PAR. A Packaging archive containing all your modules to deploy at once.
Besides the versioning of modules/bundles you also have the shared libraries and that is something I like the most. Not having to add the same libraries when working with 2 projects. Now they can just use the same shared libraries.
To help you out they also have Eclipse support so that working with the server gets easy and besides the already known Spring nature you can add to projects they also added the OSGi bundle project nature so that the manifest.mf file gets a nice editor to manage dependencies, export certain packages, etc…
For a tutorial I refer to the programming guide which contains the form tags example and that was a great help to start with.
A last note on the OSGi world is that many vendors of popular application servers are going to offer OSGi support in the next generation of server platforms.
Spring modules: XT Framework
by wouter on Oct.28, 2008, under Uncategorized
The XT Framework of the Spring Modules is a very handy framework that offers help for richer domain models and richer user interfaces. The richer domain models get help from the XT Modeling Framework that follows the Domain Driven Design by Martin Fowler. The richer user interfaces get help from the XT Ajax Framework.
The XT Modeling Framework:
- DynamicBeanIntroducer: This lets you add additional interfaces to an Object at runtime. The DynamicBeanIntroduces also implements the get/set methods.
- Collections Introductor: This uses a DynamicBeanIntroducer to add an additional interface to every contained object in a List, Set or Collection.
- DynamicFactoryGenerator: This lets you build an Object Factory by defining an interface and annotating it with the ConstructorArg annotation, the Property(getters/setters) annotation and the FactoryMethod annotation. The FactoryMethod gets called at last to create the Object.
- Notification Interface: This is used to communicate between different application layers using the message interface and the notification interface. The messages are used by the specifications.
- Specifications: The specifications pattern can be implemented using the Specification interface. Specifications are predicate like objects and besides the Specification interface Spring also offers you a way to use the Predicate from Apache Commons. The Composite Specification interface is used to combine specifications through logical operators and you can also define the Message that is used when the specification is satisfied/unsatisfied.
The XT Ajax Framework:
The XT Ajax Framework is based on Events, Handlers, Actions, Components and Responses.
The two events available are the Action events and the Submit events. You can trigger events using the javascript library from Spring XT. This provides two methods, the XT.doAjaxAction and the XT.doAjaxSubmit that are used in the onClick of an HTML component or somewhere in your javascript code.
- Ajax Handlers(Action Events): Ajax Handlers can be implemented by extending the AbstractAjaxHandler. In your Ajax handler class you implement methods returning an AjaxResponse. For example getStockExhange that returns you an AjaxResponse containing a ReplaceContentAction to refresh you table of Stock Exhanges.
- EnhancedSimpleFormController(Submit events): The SimpleFormControllers from Spring MVC can be reused by extending the EnhancedSimpleFormController, this allows you to return an AjaxModelAndView.
These Action and Submit event handlers aren’t usable without implementing an Ajax Interceptor in your Spring MVC configuration. The first step is adding a reference to the interceptor in the UrlHandlerMapping, after that is done you can define the url mappings on which an Ajax Handler and/or an Ajax validator has to be triggered.
- Validation: It is very easy to reuse the spring MVC validators by adding the DefaultValidationHandler in your Spring MVC configuration. The errors are displayed in div’s representing a single validation error or more at once. The handler also allows you to define a custom ErrorRenderingCallback and a SuccessRenderingCallback which is very handy to show messages after a submit.
- Exception handling: The exceptions that happen during an ajax call have to be catched using the AjaxExceptionHandler and these exceptions can be forwared to a page by the RedirectExceptionResolver.
- Scriptaculous and Prototype: The XT Ajax Framework also integrates with other javascipt libraries like Scriptaculous and Prototype. You can use these to add drag and drop functionalities to your pages or to show fancy effects when a validation error occurs.
I’ve used the XT Ajax Framework in a project and we added it after writing the Spring MVC controllers and the validators. The integration went very smooth but we needed a way to show messages to the user after a submit and we also wanted to use a different loading Image. The way this is done is explained in my examples which I added to the example that comes with Spring Modules.
The extended example can be downloaded here.
SCWCD 5.0(CX-310-083) experience…
by wouter on Oct.24, 2008, under Uncategorized
This week I passed my SCWCD 5.0 exam and with a score of 82%, but it was harder than expected.
The studying material I used was the Head First Servlets and JSP book from Basham, Sierra and Bates. The book covers a big part of the exam but not everything. Besides reading and studying the book you should check out the API of the servlet package, mainly the HttpServletRequest and the HttpServletResponse methods but don’t forget to peek at the Cookie methods and so on. Another API that appears on the exam is JSTL ofcourse check that API because the HF book covers a lot but not everything. I got questions about the <c:import …/> attributes and I could answer it because of the API studying.
Another small tip is about the final mock exam in the book, most people don’t score high on it because its very difficult but just take a look and try to score as high as possible but don’t use the score as a reference for the real exam :p.
Besides reading the book and the API’s also take a look at javaranch.com they have many great tips and user experiences, maybe you can ask questions there.
Between the SCWCD links on javaranch.com I also found a great overview about the J2EE patterns. It explains how to read the J2EE pattern questions from the exam and that makes them easy to answer. The exam is all about the six patterns you have to know so ignore the other patterns that come up on the exam they are there to make you go crazy :p.
If you have any other questions don’t bother mailing me
.
SCJP 6.0(CX-310-065) experience…
by wouter on Sep.23, 2008, under General
Last month I past the SCJP 6.0(CX-310-065) certification and this week I finally received all the gadgets from Sun. They really made something nice of it but I’m not planning to wear the pin or carry the sun card around
.
The preparation material I used was the book from Katherine Sierra and Bert Bates. Besides this great learning book with many mock exam questions I used the trial of Whizlabs and I gained lots of exam information on javaranch.com.
Another website that can be interesting to raise your skill level is javablackbelt.com, they also have some SCJP mock questions and lots of other Java SE questions.
The mock questions from the book and from Whizlabs were very difficult but that’s just the preparation you need. They don’t give you the number of answers you need to give, you just have to know you stuff very well.
If you have any other questions about the exam don’t mind commenting or mailing me on wouter@blackbeast.be.
Welcome on my blog…
by admin on Sep.23, 2008, under General
Welcome to everyone visiting my blog, I will be blogging about the things I learn during my professional career as a Java programmer. In July I started my first job as a Junior Java consultant @ Compuware. The project im currently working on is a timesheet management system. I will be posting more about that project in another post.
I got my bachelor degree in Applied Informatics with Application development as specialisation @ Karel De Grote Hogeschool in Antwerp. These 3 years have prepared me for the coming years but the real learning experience just has to start by working in the field.
In August I got my first Sun certification, I can now say that I am a Sun Certified Java Programmer(SCJP) for version 6.0. Next week I’m going for the SCWCD 5.0 certification and I hope that one goes as well as the first one.
Besides working I also do other stuff like riding my motorcycle(currently a Ducati 620ie), playing games, watching movies and series and doing some fitness but my personal life doesn’t have to be on this blog
. For that I suggest that you add me on facebook or linkedIn for example.

