Setter vs. Mixin injection
Please bear in mind that this is a new concept, so as with any new concept I have no idea whether it will stand the test of time (as have constructor and setter injection), but it’ll be interesting to find out :->
On the whole I think constructor injection is the best way to go. It provides a clear API for the dependencies of each bean in the init() method, which I think is a best practice. However, sometimes constructor injection doesn’t work – especially if you have circular dependencies.
Traditionally in Spring and then in ColdSpring, the solution was a “hack” called setter injection where you create a set%ObjectName%() method which is used to inject the appropriate object into the bean that requires it after construction but before returning it. The biggest problem with this is that you are left with a bunch of setter methods that shouldn’t really be there. The intent is not to allow your application code to set the object but just to allow your DI engine to function. Because of that, the API can become a little confusing (especially with transients) as it is not clear whether a setter is for injection purposes or for traditional setting purposes.
I have added a new type of injection to LightWire called mixin injection. The idea is to be able to resolve circular dependencies without having to add methods to an objects API that are purely for the purpose of construction. With mixin injection, you just provide a comma delimited list of all of the mixin dependencies and LightWire automatically injects them using a mixin method it dynamically attaches to every bean it creates (mixinObject()) - without requiring the setter methods. This saves a bunch of typing of setter methods but also (more importantly) keeps the bean APIs cleaner by removing setters that only existed for construction purposes.
Mixin injection doesn’t allow for autowiring, but typing the name of a bean in the LightWire config is less work than creating the setter method, and by putting that information in the config file, that file stays as a definitive resource of object dependencies which to me is preferential to using autowiring.
The only definitive limitation with mixin injection when compared to setter injection is that it can only inject the objects – not do anything with them. If you have setter injection with smart setter methods that do more than just set variables.ObjectName = arguments.ObjectName, setter injection is still probably the best approach (which is why LightWire still supports setter injection). If not, I think you should consider the possibilities of mixin injection. Any thoughts?!



There are no comments for this entry.
[Add Comment]