刻板印象的解释:
@Service
- 使用@Service 注释所有服务类。该层知道工作单元。您所有的业务逻辑都将在服务类中。通常,服务层的方法都包含在事务中。您可以从服务方法进行多次 DAO 调用,如果一个事务失败,所有事务都应该回滚。
@Repository
- 使用 @Repository 注释所有 DAO 类。您所有的数据库访问逻辑都应该在 DAO 类中。
@Component
- 使用组件构造型注释您的其他组件(例如 REST 资源类)。
@Autowired
- Let Spring auto-wire other beans into your classes using @Autowired annotation.
@Component
is a generic stereotype for any Spring-managed component. @Repository
, @Service
, and @Controller
are specializations of @Component
for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.
Reasons to use them :
- The main advantage of using @Repository or @Service over @Component is that it's easy to write an AOP pointcut that targets, for instance, all classes annotated with @Repository.
- You don't have to write
bean
definitions in context xml file. Instead annotate classes and use those by autowiring.
- Specialized annotations help to clearly demarcate application layers (in a standard 3 tiers application).
Now, Practically performance impact of using context xml beans & annotations is the same. Component scanning is a bit more expensive (when you scan for @Service, @Component). The annotations are 'parsed' with reflection, the xml - with an xml parser. But, as you said, it is startup-time - it happens only once. And on a moderate machine it starts pretty quickly even with annotations.