@Autowired tells Spring to inject a dependency automatically. Spring finds the bean whose type matches the field or parameter, which is matching by type, and passes it in.
You can put it on:
- constructors
- setter methods, and other methods with any name
- fields
- method parameters
@Service
public class UserService {
@Autowired
private UserRepository userRepository; // Field injection
@Autowired
public UserService(UserRepository userRepository) { // Constructor injection
this.userRepository = userRepository;
}
}
The example uses two places at once only to show both. In real code you pick one, usually the constructor. When a class has a single constructor, that constructor needs no @Autowired.
Every place Spring fills is required by default, so startup fails when no bean matches. Use @Autowired(required = false) or Optional for an optional dependency. When several beans match, choose one with @Qualifier or mark one bean @Primary.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓