简体   繁体   中英

How can i implement Factory pattern without using if else or switch case in spring using annotations

i am learning spring.. i have gone through online resources and implemented factory pattern by using switch case...

Interface:

public interface Printer {
   public void print();
}

Implementation calsses:

public class Printer1 implements Printer {
   public void print() {
      System.out.println("Printer-1");
   }
}

public class Printer2 implements Printer {
       public void print() {
          System.out.println("Printer-2");
       }
 }

How can i load particular object based on user input?

is there any way to implement factory pattern in spring using annotations ?

If you want some member of your class to be dynamically initialized\\populated on every call to the corresponding getter, you can try the Lookup Method Injection as described here . Check "3.4.6.1 Lookup method injection"

So even if the class that contains the dynamic member was created in scope=singletone (the default for spring bean container) every time you will access the field that has a lookup method assigned, you will get an appropriate object according to the business logic implemented inside the lookup method. In your case the Printer is an interface so you can easily implement the validation inside your lookup method and return a validated object.

When you configure your Main class, assign a lookup method to its member(s) that implement(s) Printer interface - it will be called whenever you need a new instance of the bean that implements 'Printer'.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM