I am developing a web application using spring-mvc.
Now the @Controller, @Service and @Repository stereotypes are available.
I found @Controller particulary
Component scan saves you from defining each bean manually via xml or java configuration.
Multiple stereo types are there to define layers like service layer, data layer, etc. Also based on different stereo types if you want to do something specific then you can do so.
Explanation of stereotypes :
@Service
- Annotate all your service classes with @Service. This layer knows the unit of work. All your business logic will be in Service classes. Generally methods of service layer are covered under transaction. You can make multiple DAO calls from service method, if one transaction fails all transactions should rollback.@Repository
- Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.@Component
- Annotate your other components (for example REST resource classes) with component stereotype.@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 :
bean
definitions in context xml file. Instead annotate classes and use those by autowiring.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.