Spring vs Java 反射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11710430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:07:17  来源:igfitidea点击:

Spring vs Java reflection

javaspringreflection

提问by Bee

I need to create objects dynamically. I use Spring to create a map of class names. Now I can use

我需要动态创建对象。我使用 Spring 创建一个类名映射。现在我可以使用

Spring ApplicationContext.getbean(className)

春天 ApplicationContext.getbean(className)

or

或者

Java Class.forName(className).newInstance().

爪哇Class.forName(className).newInstance()

Which method is more efficient?

哪种方法更有效?

Thanks you.

谢谢。

采纳答案by JB Nizet

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.

如果 spring bean 是原型范围的 bean,则 Spring 必须使用反射实例化它,因此必须执行第二个代码段所做的操作。但是要求 Spring 上下文获取 bean 并不仅仅为您提供一个类的新实例。它返回一个 Spring bean,您可以在该 bean 上应用方面(安全性、事务性等)、注入的依赖项等。

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

你不应该根据性能来选择调用什么,而应该根据你想得到什么来选择。无论如何,与您的应用程序执行的其他操作(网络调用、数据库查询等)相比,这两个调用的成本可能可以忽略不计。

回答by micha

The spring solution also resolves dependencies in the created obects for you. You can also have a look in the Spring lookup method injectionfeature

spring 解决方案还为您解决了创建的对象中的依赖关系。您还可以查看Spring 查找方法注入功能

回答by Lawrence McAlpin

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.

如果它是 Spring 管理的 bean,则需要通过 ApplicationContext 创建它,否则将不会填充依赖项。如果它不是 Spring bean,而只是一个普通的 Java 对象,那么这是不必要的开销,因此您可以使用后者。