Autowiring in Spring makes life easy for the developer as the Spring container takes up the responsibility of autowiring relationships between collaborating beans by referring the contents of the ApplicationContext. Spring autowiring brings certain advantages at the same time autowiring has certain limitations and disadvantages. In this post we’ll have a look at both.
Advantages of autowiring in Spring
- By using Autowiring there is a significant reduction in the explicit configuration needed to specify properties or constructor arguments.
- By using autowiring maintaining code and evolution of code is easy as configuration is updated automatically. For example, if you need to add any new dependency to a class, that dependency can be satisfied automatically, you do not need to modify the configuration explicitly.
Limitations and Disadvantages of Spring Autowiring
- If you are using autowiring it should be used consistently across a project. If autowiring is used to wire only one or two bean definitions, it might be confusing to developers and make code less readable where developer has to refer multiple sources to see the relationships among beans.
- Autowiring can’t be used to autowire simple properties such as primitives, Strings, and Classes (and arrays of such simple properties). This limitation is by-design.
- One of the limitation of autowiring is that Explicit dependencies in property and constructor-arg settings always override autowiring.
- Autowiring is less exact than explicit wiring. In case where Spring container can’t determine the exact bean to be autowired it won’t try to guess an exception is thown instead.
- For dependencies that expect a single value, if there are Multiple bean definitions matching that dependency type within the container then this ambiguity is not arbitrarily resolved in case of autowiring. If no unique bean definition is available, an exception is thrown.
- Wiring information may not be available to tools that may generate documentation from a Spring container.
- Exclude Bean From Autowiring in Spring
- Spring Autowiring Example Using XML Configuration
- Setter Dependency Injection in Spring
- Injecting Null and Empty String Values in Spring
- Spring Bean Scopes
- Spring @Conditional Annotation
- Spring Boot + Spring Data JPA + MySQL + Spring RESTful
- Spring Boot and Dependency Injection
That’s all for the topic Advantages and Disadvantages of Autowiring in Spring. If something is missing or you have something to share about the topic please write a comment.
You may also like