2

I just start to study Spring and I have a question:

In order to inject a bean, when is it better to use property-based dependency injection:

 <bean id="myFirstClass" class="..."> <property name="targetProperty"> <bean id="TheBeanIwantToInject" class="..."/> </property> </bean> 

instead of constructor-based dependency injection

<bean id="myFirstClass" class="..."> <constructor-arg ref="TheBeanIwantToInject"/> </bean> 

or it's just two equivalent solutions?

1
  • 1
    This is kind of a religion... You should do whatever you prefer yourself. Commented Apr 28, 2013 at 19:02

3 Answers 3

4

If you want to create immutable objects then the constructor-arg variant is the only option. I prefer that one.

Sign up to request clarification or add additional context in comments.

8 Comments

Well, that's not entirely true. With Java Config, you can autowire private fields.
@NilsH Even final fields? If so then I agree and will remove my answer.
@NilsH You do not need to use Java Config to autowire private fields, it can be done via 'classic' xml config too.
No, that would give a compilation error (since it is not initialized). Nothing Spring can do about that. However, declaring a field final doesn't really make or make not an immutable object. However, I agree with your answer. I prefer it as well. But it is a lot of personal preferences involved.
I'd prefer constructor injection, because it doesn't force me to add setters to my object if I don't want to.
|
2

if you have bidirectional dependencies you will need one of them to be property injected. usually though you should think about your architecture if you have such a case. the interdependency could be extracted in a new class for example

Comments

1

You need to honestly look at what you are doing in the code and what makes sense. From a pure OO perspective, if you need the dependency for your class to work and it should never be changed, used constructor injection. If you need a default dependency but it might change (or an optional one), use properties.

This is a holy war type question however. Should I use XML or Autowire, should I inject via properties or constructor. The real key is be consistent. If you are consistent, it will make sense to the next poor developer that has to work in your code even if it isn't technically correct according to OO principles. If you are inconsistent, I feel sorry for the next guy.

My preferences, not that it matters, is to use constructor injection as much as possible, it allows me to have cleaner code without all the getters and setters that may break encapsulation logic.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.