Advantages of using spring stereotypes?

前端 未结 2 2054
天命终不由人
天命终不由人 2020-12-12 17:17

I am developing a web application using spring-mvc.

Now the @Controller, @Service and @Repository stereotypes are available.

I found @Controller particulary

相关标签:
2条回答
  • 2020-12-12 18:04

    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.

    0 讨论(0)
  • 2020-12-12 18:16

    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 :

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

    0 讨论(0)
提交回复
热议问题