What are the advantages of constructor autowiring over normal autowiring or property autowiring?

Constructor autowiring has advantages in that you can make the wired in fields final (particularly useful if your bean will be called from multiple threads as threadsafety is easier to analyse with finals). And you can ensure that the bean is always constructed in a valid way (although you can always implement InitializingBean and use the afterPropertiesSet method to achieve the same if you’re wiring in properties).

One of them is that when testing, doing a mock over a constructor is easy, but over properties it’s a little bit hard

ule of thumb: stick to constructor injection. Why? A constructor specifies the required dependencies of the class being instantiated. With setter/field injection on the other hand, you always have to look them up (by looking at the source code). You may run into troubles (eg NPE’s) because an instance misses some required dependencies. Have a look at

Leave a Reply

Your email address will not be published. Required fields are marked *