tags:

views:

616

answers:

4

My model layer is being used by a handful of different projects and I'd like to use a single XML Spring Configuration file for the model regardless of which project is using it.

My question is: Since not all beans are used in all projects am I wasting resources to any significant amount if there not being instantiated? I'm not too sure how lazy Spring is about loading them since it's never been an issue until now.

Any ideas?

A: 

By default Spring beans are singletons and are instantiated when the application context is created (at startup). So assuming you haven't overridden the default behaviour, then a single instance of every bean will be created.

Don
A: 

Depends upon the objects.

But, unused code is 'cruft' and will increase the cost of maintenance.

Better to delete the refs and classes. You can always restore from version control if they are needed later.

willCode4Beer
Since all the classes are used, just not in every project, deleting anything is out of the question.
Allain Lalonde
+4  A: 

Taken from the Spring Reference Manual:

The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Pre-instantiation means that an ApplicationContext will eagerly create and configure all of its singleton beans as part of its initialization process. Generally this is a good thing, because it means that any errors in the configuration or in the surrounding environment will be discovered immediately (as opposed to possibly hours or even days down the line).

However, there are times when this behavior is not what is wanted. If you do not want a singleton bean to be pre-instantiated when using an ApplicationContext, you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested.

When configuring beans via XML, this lazy loading is controlled by the 'lazy-init' attribute on the [bean element] ; for example:

<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>

But, unless your beans are using up resources like file locks or database connections, I wouldn't worry too much about simple memory overhead if it is easier for you to have this one configuration for multiple (but different) profiles.

MetroidFan2002
+3  A: 

In addition to the other comments: it's also possible to specify a whole configuration file to be lazily initialized, by using the 'default-lazy-init' attribute on the <beans/> element; for example:

<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>

This is much easier than adding the lazy-init attribute to every bean, if you have a lot of them.

Tom De Leu