
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: May 11, 2024
Arguably one of the most important development principles of modern software design is Dependency Injection (DI), which quite naturally flows out of another critically important principle: Modularity.
This quick tutorial will explore a specific type of DI technique within Spring called Constructor-Based Dependency Injection, which simply put, means that we pass the required components into a class at the time of instantiation.
To get started, we need to import the spring-boot-starter-web dependency in our pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Then we need to set up a Configuration file. This file can be either a POJO or an XML file, based on preference.
Java configuration files look similar to Java objects with some additional annotations:
@Configuration
@ComponentScan("com.baeldung.constructordi")
public class Config {
@Bean
public Engine engine() {
return new Engine("v8", 5);
}
@Bean
public Transmission transmission() {
return new Transmission("sliding");
}
}
Here we’re using annotations to notify Spring runtime that this class provides bean definitions (@Bean annotation), and that the package com.baeldung.spring needs to perform a context scan for additional beans. Next, we define a Car class:
@Component
public class Car {
@Autowired
public Car(Engine engine, Transmission transmission) {
this.engine = engine;
this.transmission = transmission;
}
}
Spring will encounter our Car class while doing a package scan, and will initialize its instance by calling the @Autowired annotated constructor.
By calling the @Bean annotated methods of the Config class, we will obtain instances of Engine and Transmission. Finally, we need to bootstrap an ApplicationContext using our POJO configuration:
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Car car = context.getBean(Car.class);
Classes with a single constructor can omit the @Autowired annotation. This is a nice little bit of convenience and boilerplate removal.
On top of that, also starting with 4.3, we can leverage the constructor-based injection in @Configuration annotated classes. In addition, if such a class has only one constructor, we can omit the @Autowired annotation as well.
Constructor injection has a few advantages compared to field injection.
The first benefit is testability. Suppose we’re going to unit test a Spring bean that uses field injection:
public class UserService {
@Autowired
private UserRepository userRepository;
}
During the construction of a UserService instance, we can’t initialize the userRepository state. The only way to achieve this is through the Reflection API, which completely breaks encapsulation. Also, the resulting code will be less safe compared to a simple constructor call.
Additionally, with field injection, we can’t enforce class-level invariants, so it’s possible to have a UserService instance without a properly initialized userRepository. Therefore, we may experience random NullPointerExceptions here and there. Also, with constructor injection, it’s easier to build immutable components.
Moreover, using constructors to create object instances is more natural from the OOP standpoint.
On the other hand, the main disadvantage of constructor injection is its verbosity, especially when a bean has a handful of dependencies. Sometimes it can be a blessing in disguise, as we may try harder to keep the number of dependencies minimal.
This brief article has showcased the basics of two distinct ways to use Constructor-Based Dependency Injection using the Spring framework.
Follow the Spring Category