I need to create objects dynamically. I use Spring to create a map of class names. Now I can use
Spring ApplicationContext.getbean(className)
or
Java Class.forName(className).newInstance()
.
Which method is more efficient?
Thanks you.
If the spring bean is a prototype-scoped bean, Spring will have to instantiate it with reflection, and will thus have to do what your second snippet does. But asking the Spring context to get a bean doesn't just get you a new instance of a class. It returns a Spring bean, on which you could have aspects applied (security, transactional, etc.), dependencies injected, etc.
You shouldn't choose what to call based on performance, but on what you want to get. Anyway, the cost of both calls is probably negligible compared to the rest of what your app does (network calls, database queries, etc.)
If it's a Spring managed bean, you will need to create it via ApplicationContext or else the dependencies won't be populated. If it's not a Spring bean, just an ordinary Java object, then that's unnecessary overhead, so you could just use the latter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With