Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring vs Java reflection

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.

like image 344
Bee Avatar asked Jul 29 '12 15:07

Bee


2 Answers

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.)

like image 90
JB Nizet Avatar answered Oct 12 '22 23:10

JB Nizet


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.

like image 44
Lawrence McAlpin Avatar answered Oct 12 '22 22:10

Lawrence McAlpin