简体   繁体   中英

Spring performance for @Autowired, @Resource and using property injection

My question is if there is any significant performance difference between the following cases of dependency injection using Spring:

  • @Resource(name=...) in the java file
  • @Autowired in the java file
  • setters in the java file and < property name="..." ref="..." /> in spring-beans.xml file

Performance should be mesured in time and is both during runtime and system initialization. Assumptions: all beans are of scope="singleton".

I'm quite new to work with Spring in this way so if I'm missing any details or if the question is irrelevant, please let me know.

Thanks

With singleton scope and a reasonable application, it shouldn't make much of a difference and unless you use a lot of lazy bean definitions, the performance difference would be located to your application startup time.

Let's take each of the three examples:

  1. @Resource injects by name so it is actually a lookup per key (fast)
  2. @Autowired is essentially a lookup per type which means that the container has to be able to know the types of the managed beans defined in the application context. This is a bit slower
  3. XML configuration in your example is a key reference (fast)

If you have a reasonable application it doest not really matter. If you have an application with 10k classes and you configured classpath scanning at the root package, classpath scanning may take some time, especially if the classes are not located in jar files (lookup by type in directories is much slower).

There's no final answer to your question except the performance cost of wiring beans is usually located in the startup phase of your application. Once the context is started, singleton beans are retrieved from a cache.

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