
- 2 ways of DI (Dependencies Injection)
- Constructor Injection:
- This method injects dependencies through the object's constructor.
- Typically, dependencies are passed as arguments to the constructor of a class.
- Injected dependencies are used within the class itself.
- Using this method, dependencies are explicitly injected when the object is created, making them clearly visible and easier to manage when changes occur.
@RequiredArgsConstructor
@Service
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
@Override
public void create(User user) {
userRepository.save(user);
}
}
- Field Injection:
- This method injects dependencies directly into the class fields.
- Injected dependencies are stored in the fields of the class, often provided externally.
- Field Injection may reduce code readability since dependencies are not explicitly shown in the constructor, and it can make testing more difficult.
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public void create(User user) {
userRepository.save(user);
}
}