Inject ColdSpring into your Beans
June 30, 2009
I've recently discovered that ColdSpring has the ability to inject itself into any of the singletons that it manages. Most of the time you would have no need to do this as normally you pass beans (instances of a CFC) into other beans either using ColdSpring's auto-wire capabilities or by defining them with property nodes.
Occasionally it is useful for a bean to be BeanFactoryAware, which simply means that it knows about the beanfactory (ColdSpring) and can call it's getBean method. This is dead handy if you ever want to dynamically get a bean defined in ColdSpring at runtime. For example I have an abstract Service class (that is extended by all my concrete services classes). In it I want to be able to get the correct gateway for the concrete service. Originally I did this by passing in a map of all my gateways to each service defined in ColdSpring but this gets a bit messy quite quickly.
When ColdSpring instantiates each bean, it will look for a method called setBeanFactory, and if it finds it then ColdSpring will inject the beanFactory into your bean.
So, I simply added a method to my AbstractService.cfc called setBeanFactory, and here it is:
function setBeanFactory( factory )
{
variables.beanFactory = arguments.factory ;
}
This attempt failed horribly and it took me a while and some digging through the ColdSpring code to find out why. What ColdSpring does is to read the meta data of each class it instantiates. If it finds a setBeanFactory method, it knows to inject iteself into it. However, (and this is what caught me out, it also checks the meta data of the arguments that setBeanFactory is expecting. As I'd written my code in cfscript, ColdSpring wasn't seeing that the factory argument expected a coldspring.beans.BeanFactory.
A quick change to use cfml tags and it was up and running, so here is the working setBeanFactory method:
<cffunction name="setBeanFactory"
access="public"
returntype="void"
output="false"
hint="If Coldspring finds this method it will inject the beanfactory into this object. ">
<cfargument name="factory"
type="coldspring.beans.BeanFactory" />
<cfset variables.beanFactory = arguments.factory />
</cffunction>
One other gotcha to look out for is that ColdSpring calls all the setters (where appropriate) before it calls the init method, so if you set any values in your init, that have already been injected, then they will be overwritten.
- Posted in:
- ColdFusion
- Coldspring
No comments
Leave a comment
If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)




