- 2 ways of DI (Dependencies Injection)

     

  1. 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);
}
}



  1. 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);
}
}












한국정보시스템개발원 |
Hankook Information System Institute

austiny@snu.ac.kr / austiny@gatech.edu