tags:

views:

315

answers:

4

Wicket has this device called a lazy proxy factory. Given:

<property name="foo" ref="beanx"/>

the idea is to auto-generate a proxy in place of 'beanx', and then only initialize beanx if and when something actually calls a method on it.

It seems as if this might be a core Spring capability. Is it there somewhere?

A: 

Spring singleton beans, the closest thing to what you want, are created when the spring context is initialized: http://static.springsource.org/spring/docs/2.0.x/reference/beans.html#beans-factory-scopes. So I believe the short answer is "no." You can implement your own scope to do this by extending the Spring classes quite easily, though.

Zach
A: 

Spring session/request scope is implemented using the technique you describe, but it is only intended to handle transitions between scope cardinalities, not instance creation. So spring uses the same concepts, but you'd probably have to create your own implementation.

krosenvold
+2  A: 

There is no direct equivalent of this in Spring, although there are various techniques that are similar, and may fit your requirements.

  • You can use lazy-init="true" on a bean definition, which will defer instantiation of the bean until it is first referenced. However, if another bean has a reference to your lazy-init bean, then that will trigger the instantiation, unless the referring bean is itself lazy-init, and so on. This doesn't work too well in practise, since it's all to easy to "collapse" the lazy-init chain with a single accidental reference.
  • Beans can have various "scopes", which out-of-the-box includes singleton, prototype, and (for webapps) request and session scopes. These allow you to control the lifecycle of the bean, but it sounds like you do need a singleton-scoped bean, but with deferred initialization, and scoped beans won't help you much there.
  • You could build something to do what you need by using Spring AOP, but it would be quite awkward, I think.

Thinking about it, it's quite surprising that Spring can't do this easily.

skaffman
lazy-init is not quite lazy enough in this case. There is a proxy factory in AOP, and there is the proxy factory in Wicket. I just couldn't believe that this 'extra-lazy' trick wasn't in core Spring.
bmargulies
+1  A: 

See LazyInitTargetSource; that might do what you want. It requires use of lazy-init="true" on the target bean as well, though.

Michael