SimpleInject usage

1 Feb

Now that the code of SimpleInject has been cleaned and documented I can present how to use it.

The repository can be found here and for this article I’m using the this revision.

The goal is provide an easy way to trigger a method and inject parameters from a context. It can be used to build a plugin mechanism as I show in this post and it’s rely on the JSR 330 api.

First of all the source code of the example :

This plugin will iterate through all string passed as parameter and will display the value on the standard output. The init method will be execute because it’s annotated with @javax.inject.Inject . If the context contain an object of type String[] it will be injected as parameter.

 

This plugin do exactly the same thing as the previous one but the parameter is of type Object. To inject this parameter the @javax.inject.Named will be used and an object which has been register to the context with the name “arguments” will be used.

 

This where everything is tied together. First of all we need to instantiate a new InvokerRepository (line 12) and a Context (line 13). We add to the context the variable args and it will be associated with the name “arguments” (line 14). After this we can instantiate our plugins (line 15 to 16). Finally we can invoke our plugins as shown on line 19. the getInvoker(…) method will return an object of type org.knard.SimpleInject.Invoker that is used to call method annotated in our plugin. Object return by the getInvoker(…) method are stateless and can be reused. These Invoker can be cached to improve performance and the org.knard.SimpleInject.InvokerRepositoryCached.InvokerRepositoryCached is already managing a cache of Invoker if you need some performance improvement.

That’s all, nothing complex as said in the name.

Leave a Reply

Your email address will not be published. Required fields are marked *