Dependency Injection (DI) allows objects to get their required dependencies (other objects or components they need to work) from an external source, instead of creating those dependencies themselves. An understanding in Spring XML configuration is recommended before the Java based configuration.
Setter injection
In Java based configuration you can inject attributes and dependencies using object’s public setter methods.
Primitive attribute injection
The Person
object has a field age
, you do so in the configuration class to inject primitive attribute.
@Configuration
public class AppConfig {
@Bean
public Person person() {
Person obj = new Person();
obj.setAge(25);
return obj;
}
}
public class Person {
int age;
public void setAge(int age) {
this.age = age;
}
}
Reference attribute injection (Wiring)
In Spring’s Java-based configuration, we can inject the required dependencies into a bean if it depends on other beans. To ensure the code remains loosely coupled, we avoid instantiating objects directly within configuration methods. Instead, we define these dependencies as separate beans and define them as arguments to the configuration methods. The IoC container manages these dependencies, passing them as parameters.
The Person
object has a dependent Computer
.
@Configuration
public class AppConfig {
@Bean
public Person person(Computer com) {
Person obj = new Person();
obj.setAge(25);
obj.setComp(com);
return obj;
}
@Bean
public Computer computer() {
return new Computer();
}
}
Excluding a bean from autowiring
Excluding a bean from autowiring by setting the autowireCandidate
attribute of the Bean
annotation to false.
@Bean(autowireCandidate = false)
public Desktop desktop() {
return new Desktop();
}