0

Is there a better way to create objects using spring autowiring or any other design patterns?

I have 100 different types of events, I am trying to avoid repeating case statement 100 times.

ViratKohli
  • 333
  • 1
  • 3
  • 16
  • In order not to write if or case statements, you should build a polymorphic structure. Create an interface and implement it with your events. Then you can have all the objects that implements that interface with java reflection. check this: http://stackoverflow.com/questions/435890/find-java-classes-implementing-an-interface – Neron Jun 17 '16 at 17:12

1 Answers1

0

Declare an ApplicationContext:

@Autowired 
ApplicationContext context;

Then do an:

EventBean event = (EventBean) context.getBean(eventType);

You will have to name the event beans so the type matches their name.

Guillaume F.
  • 5,905
  • 2
  • 31
  • 59
  • can you explain? how does context.getBean check the condition eventType and create appropriate object ? constants are defined with three character values; cancel = cxe, create = cre etc – ViratKohli Jun 17 '16 at 16:37
  • Your beans have one or many names, by default the name of the method you used to create them, or the name of the class. `getBean()` looks for a bean which matches the name you pass in parameter. So, if your constant `CANCEL_EVENT` matches `CancelEventBean`, it will return that type of event. – Guillaume F. Jun 17 '16 at 16:54
  • they won't match. they are different and I can't control constant values. – ViratKohli Jun 17 '16 at 17:00
  • You have to make it match somehow. Either rename or add a name to the beans themselves, or create your own constants. You can't expect Spring to guess which bean without at least a clue. – Guillaume F. Jun 17 '16 at 17:05