Skip to content

Instantly share code, notes, and snippets.

@robert-niestroj
Created September 1, 2023 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robert-niestroj/425f8d9967ad594a1260844279e09a89 to your computer and use it in GitHub Desktop.
Save robert-niestroj/425f8d9967ad594a1260844279e09a89 to your computer and use it in GitHub Desktop.
SpringBeanByEnum
public enum Plan {
FREE, EXPRESS, PROFESSIONAL, ENTERPRISE
}
public class Customer {
long id;
String name;
Plan plan;
}
public interface PdfGenerator {
byte[] generatePdf();
Plan forPlan();
}
@Service
class FreePdfGenerator implements PdfGenerator {
byte[] generatePdf() {
return [];
};
Plan forPlan() {
return Plan.FREE;
}
}
...
@Service
class EnterprisePdfGenerator implements PdfGenerator {
byte[] generatePdf() {
return [];
};
Plan forPlan() {
return Plan.ENTERPRISE;
}
}
@Service
class InvoiceService {
List<PdfGenerator> pdfGenerators; //Spring injects here all 4 PDF Generators
public createInvoice() {
Customer customer = getCurrentCustomer();
PdfGenerator pdfGenerator = getPdfGeneratorForPlan(customer.getPlan()); //here i chose the one generator from the List
var pdf = pdfGenerator.generatePdf();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment