I have configured a Spring app (using Camel for integration with an ActiveMQ broker) such that two particular classes, say, Person and Personality, get wired-up and injected with all of their dependencies automatically through the Spring container. For the sake of this example, Person objects have Personality objects as members/properties. So the Spring config file wires up Personality instance, and those beans are referenced in the wired People beans:
<bean id="personality" class="com.me.someProgram.Personality" singleton="false">
<!-- blah... -->
</bean>
<bean id="person" class="com.me.someProgram.Person" singleton="false">
<!-- People have Personalities -->
<property name="personality" ref="personality"/>
<!-- blah... -->
</bean>
Both beans are specified as prototypes in scope because this makes sense for my application. Basically, I need to grab a new instance of Personality every time I get a new Person.
My question:
This is my first application using Spring, and IoC/dependency injection in general. I am worried about garbage collection and memory leaks. When beans are prototypes, and you have prototypes nested inside of prototypes (via has-a relationship), do you have to worry about GC/memory leaks? Or does the Spring container alleviate all of those concerns for you? Are there best practices with regards to Spring/IoC memory management? Any anti-patterns to steer clear of?
My actual business objects are quite large, and I will produce many of them, so if I start heading down a road that is riddled with bad memory management, it’s going to be a very, very bumpy ride.
Thanks!
There will be no issues with garbage collection in the above code that are caused by spring. You can think of the spring config above as another way of saying,
Spring does not maintain a reference to prototype beans it creates, so spring itself will not cause a memory leak.
Spring does maintain references to singleton scoped beans, and those will not be gc’d until the containing application context is.