Reputation: 245
OK. I am officially frustrated with Spring core. First let me lay out an example. You have three classes: Main, Person, and Address. Main is the class containing the main method (the driver so to speak). Let us assume that every Person has an address or rather needs an address to function. It is a dependency. I understand that we can use Spring to “wire” these beans together via constructor or setter. Let’s assume we did it by constructor.
<bean id="address" class="vail.Address" />
<bean id="person" class="vail.Person">
<constructor-arg ref="address" />
</bean>
OK, so here is where I get lost. In my research (mostly through tutorials) I have only seen two options from this point. However, I will add a third:
Is there any way this is correct. That seems like way to much trouble to go through for decoupling Main and Address. Any help in this matter would be much appreciated.
Upvotes: 1
Views: 1753
Reputation: 41143
Your requirement looks very vague. A class named Person is typically used to represent persisted domain object (eg: a person instance stored in memory, database, xml etc). Normally setting a person's instance attribute wouldn't be classified as 'hardcoding'.
Where dependency injection comes handy is when you have to manage dependency / reference accross many class instance.
For example assuming your program is a web application with a controller class PersonController and in order to lookup person instance from database you use PersonDAO class, then your spring config might look like this
<bean id="personDAO" class="myapp.PersonDAO"/>
<bean id="personController" class="myapp.PersonController">
<property name="personDAO" ref="personDAO"/>
</bean>
Note how inside PersonController class you are free from boilerplate code to find / create PersonDAO. You don't have to think which class should be created first and which should reference which. Such thing would start to be a nightmare when you have 10+ classes (common in enterprise app).
This get more powerful when you also use annotation based autowiring.
Upvotes: 1
Reputation: 57202
I think you might be misunderstanding why you might use spring. You use it typically to inject predefined instances of an object. If you need dynamically created people, you wouldn't create those in bean files.
An example would be
<bean id="DatabaseService" class="some.specific.DatabaseService"/>
<bean id="DataRetriever">
<constructor-arg><ref bean="DatabaseService"/></constructor-arg>
</bean>
Here there is a data retriever bean that presumably other beans use for retrieving data. The database service is wired in in case it changes. You could connect to different databases (or mock out the database service).
Your case is you are trying to wire in specific people - that's not typically why you would use dependency injection.
Upvotes: 5