1. Use @autwired to inject a value into the class field

Let’s start by defining the classes for two objects: Person and Parrot.

@Component 
public class Parrot {
private String name = "Koko"; 
// Omitted getters and setters 
@Override 
public String toString() { return "Parrot : "+ name; }}Copy the code

We instruct Spring to provide a value for this field from its context. Spring creates two beans, Person and Parrott, and injects the parrot object into the fields of the bean of type Person.

The definition of the Person class:

@Component 
public class Person {
private String name = "Ella"; 

// We annotate the field with @autwire to instruct Sp Ring to inject the appropriate value from its context.
@Autowired 
private Parrot parrot; 
// Omitted getters and setters 
}`
Copy the code

I have added beans in the Spring context of this example using stereotype annotations. I could have used @bean to define beans, but in a real-world scenario, the most common thing you’ll encounter is @Autwired with a stereotype annotation

Configuration class definition:

@Configuration 
@ComponentScan(basePackages = "beans") 
public class ProjectConfig {}Copy the code

Main class definition:

public class Main{ 
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext (ProjectConfig.class); 
Person p = context.getBean(Person.class); 
System.out.println("Person's name: " + p.getName()); 
System.out.println("Person's parrot: " + p.getParrot());
}
} T
Copy the code

Output:

Person’s name: Ella

Person’s parrot: Parrot : Koko

Disadvantages:

You cannot choose to make this field final

@Component 
public class Person {
private String name = "Ella"; 
@Autowired
private final Parrot parrot;
}
Copy the code

This doesn’t compile. A final field cannot be defined without an initial value.

2. Use @autwired to inject a value through the constructor

When Spring creates a Bean, the second option for injecting values into object properties is to use the constructor of the class that defines the instance. This approach is most commonly used in production code. It enables you to define fields as final, ensuring that no one can change their value after Spring initializes them.

3. Use dependency injection through setters

You won’t often find developers using setters for dependency injection. This approach does more harm than good: it’s more challenging to read, doesn’t allow you to determine final fields, and doesn’t help simplify your testing.

@Component 
public class Person { 
private String name = "Ella"; 
private Parrot parrot; // Omitted getters and setters
@Autowired 
public void setParrot(Parrot parrot) { 
this.parrot = parrot; }}Copy the code

Reference books

Spring Start Here (manning.com)