How is bean injection done in Spring?
In Spring, there are three common ways to inject beans: constructor injection, setter injection, and field injection.
- Constructor injection: Dependency injection is achieved by using the @Autowired or @Inject annotation on the class constructor. When the Spring container creates a bean, it automatically checks the constructor parameters and injects the matching dependencies into the constructor. For example:
@Service
public class UserService {
private UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
- Setter injection: Dependency injection can be achieved by using the @Autowired or @Inject annotation on the setter methods of a class. When the Spring container creates a bean, it automatically calls the corresponding setter method and injects the matching dependency into the property. For example:
@Service
public class UserService {
private UserRepository userRepository;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
- Field injection: Dependency injection is achieved by using the @Autowired or @Inject annotation on the fields of a class. When the Spring container creates a bean, it automatically injects the matching dependencies into the fields. For example,
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
}
In addition to the common injection methods mentioned above, you can also use the @Inject annotation from the JSR-330 specification or the @Qualifier annotation from Spring to specify specific dependency injections. Additionally, you can use the @Bean annotation in Java configuration classes to define beans and inject them into other beans.