Thursday 21 February 2013

Spring Fakes

Ok this isn't rocket science but as it stumped me for a little while I thought I would share.

Essentially what I am trying to do is to replace a real interface with a fake so I can integrate the parts of my application without having the real implementation of the interface.

Specifically I am implementing a protocol for registering certificates but I don't have the implementation of the configuration yet. The interface is there but the implementation is ropey at best and the GUI for putting the configuration in the DB is a while off.

So I created a fake that hard-codes a configuration. The trick is how to wire this in without removing the real implementation jar (as the interface lives in there).

In Spring the XML configuration trumps the annotations. Most of the application uses the @Component and @Autowired annotations to tie it all together. I figured if I declared a bean in the XML it would override the real one.

Well yes but no. For some cases it seemed to work (that is some cases didn't throw errors) but in other cases it did. The trick it turns out is that even though auto-wiring is configured to be type based, the replacement is name based.

Basically to get it to work I had to make sure that the name of the config interface instance was always consistent and matched the bean ID in the XML. Then Spring would happily use the specified instance instead of getting confused over having multiple implementations.

No comments:

Post a Comment