Skip to content

Instantly share code, notes, and snippets.

@dwelch2344
Created March 29, 2016 03:57
Show Gist options
  • Save dwelch2344/4c513a330728c566c92b to your computer and use it in GitHub Desktop.
Save dwelch2344/4c513a330728c566c92b to your computer and use it in GitHub Desktop.
// please don't ever do this.
public class ManualDependencyInjectionDemo {
@Getter @Setter
public static class UserService {
public User getUser(String username){
// ...
}
}
// correlates customer details with a user account
@Getter @Setter
public static class CustomerService {
private UserService userService;
private PaymentService paymentService;
private CustomerRepo repo;
public CustomerDetails getDetails(String username){
User user = userRepo.getUser(username);
Customer customer = repo.findByUserId(user.getId());
List<Payment> payments = paymentService.findPayments(customer.getId());
customer.setPayments(payments);
return customer;
}
}
public static class PaymentService {
public List<Payment> findPayments(Long customerId){
// ..
}
}
@Getter
public static class Injector {
private UserService userService;
private PaymentService paymentService;
private CustomerRepo customerRepo;
private CustomerService customerService;
public void init(){
// step 1: create your instances
userService = new UserService();
paymentService = new PaymentService();
customerRepo = new CustomerRepo(); // you get the idea...
customerService = new CustomerService();
// step 2: wire up their dependencies
customerService.setUserService(userService);
customerService.setPaymentService(paymentService);
customerService.setRepo(customerRepo);
// step 3: at this point, everything should be wired up
// so now your app can function
}
}
public static void main(String[] args){
Injector di = new Injector();
di.init();
CustomerService fullyWiredService = di.getCustomerService();
CustomerDetails details = fullyWiredService.getDetails("Tyler Evans");
// success!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment