Spring Boot supports various ways to inject beans, and the following are three commonly used methods:
1. Constructor Injection
Using constructor injection is a type-safe, clear and clear way to ensure the integrity of the bean. Define a constructor in the class and declare the Bean object to be injected in its parameter list. Spring will automatically pass the corresponding bean object in when initializing the bean.
Sample code:
```java
@Service
public class MyService {
private final MyRepository myRepository;
public MyService(MyRepository myRepository) {
= myRepository;
}
// ...
}
```
2. Attribute injection
Property injection is a common way of injection, implemented using the `@Autowired` annotation. Add the `@Autowired` annotation on the class's properties, and Spring will automatically inject the corresponding Bean object. It should be noted that property injection may cause incompleteness of the Bean state because they are injected only after the constructor, so there may be problems such as null pointer exceptions.
Sample code:
```java
@Service
public class MyService {
@Autowired
private MyRepository myRepository;
// ...
}
```
3. Method injection
Method injection is a flexible way of injection, defining a method in a class and declaring the Bean object to be injected in its parameter list. Use the `@Autowired` annotation to mark this method. Spring will automatically call the method when initializing the bean and pass it into the corresponding bean object.
Sample code:
```java
@Service
public class MyService {
private MyRepository myRepository;
@Autowired
public void setMyRepository(MyRepository myRepository) {
= myRepository;
}
// ...
}
```
It should be noted that method injection should not be called in the constructor, because they are called only after the constructor, and problems such as null pointer exceptions may occur.