@autoWired supports annotations on constructors/parameters/methods/attributes

The test class

  • The Boss is injected into the class
  • Assistant injection class
@Component public class Boss { private Assistant assistant; public Assistant getAssistant() { return assistant; } public void setAssistant(Assistant assistant) { this.assistant = assistant; }}Copy the code
@Component public class Assistant { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; }}Copy the code

The first type of property injection

@Autowired
private Assistant assistant;
Copy the code

The second method is injection

  • When the method is injected, the Assistant Assistant takes the corresponding object from the container and executes the method
@Autowired
public void setAssistant(Assistant assistant) {
    this.assistant = assistant;
}
Copy the code

The third constructor injection

When the container is started, the container calls take object injection,

@Autowired
public Boss(Assistant assistant) {
    this.assistant = assistant;
}
Copy the code

If there is only one argument, @autowired can be omitted

public Boss(Assistant assistant) {
    this.assistant = assistant;
}
Copy the code

The fourth kind of parameter injection

  • Inject the same meaning as the constructor
public Boss(@Autowired Assistant assistant) {
    this.assistant = assistant;
}
Copy the code

Injection of bean

For example, Boss and Assistant are beans placed in ioc containers via @Component. What about @bean annotations? It can also be injected automatically

@bean public Color Color(Assistant Assistant) {@bean public Color Color = new Color(); color.setAssistant(assistant) return color; }Copy the code