Created
March 29, 2016 03:57
-
-
Save dwelch2344/4c513a330728c566c92b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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