简体   繁体   中英

Spring: Why use @Service classes instead of Singleton objects?

We're using Scala with Spring Boot, so creating Singleton objects is as simple as using the Scala 'object' keyword instead of the 'class' keyword, and filling it with whatever functions are needed. So far, it seems that Singleton objects can do the same thing as @Service classes, and also has the extra benefit of avoiding circular dependency errors during dependency injection. Is there any reason to use @Service classes over Singletons?

Annotating classes with @Service means that a Spring-managed bean will be created for such classes. By default, they are also singletons. However, being Spring-managed beans make it possible to use Spring-related features, such as:

  • Dependency injection (being this bean injected in other Spring-managed beans and also inject other Spring-managed beans into this one);
  • Spring AOP (allowing, for example, the usage of @Transactional );
  • Application context changes awareness (you could make your @Service implement ApplicationListener so that you can do something based on Application related events);
  • etc...

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