在很多網路上的範例程式,常常都會看許多相同的場景卻用到到各種不同的寫法,最常見的就是Spring的Annotation,到底什麼時候該用什麼樣的annotation呢?
參考stackoverflow這篇文章 What is the most appropriate way of injecting daos in services, services in controllers in Spring? 的解釋:
@Service and @Repository are just "sub-annotations" for @Component to specify the bean a bit more (to separete Services from Repositories for more sophisticated stuff). From the point of injection this three are equal.
For injection, there are 3:
- @Resource (JSR-250)
- @Inject (JSR-330 --> Google-guice)
- @Autowired (Spring only)
詳細的比較可以參考Spring 3.1 - beans-standard-annotations-limitations
Table 4.6. Spring annotations vs. standard annotations
Spring | javax.inject.* | javax.inject restrictions / comments |
---|---|---|
@Autowired | @Inject | @Inject has no 'required' attribute |
@Component | @Named | — |
@Scope("singleton") | @Singleton |
The JSR-330 default scope is like Spring's prototype .
However, in order to keep it consistent with Spring's general defaults,
a JSR-330 bean declared in the Spring container is a
singleton by default. In order to use a
scope other than singleton , you should use Spring's
@Scope annotation.
javax.inject also provides a
@Scope annotation.
Nevertheless, this one is only intended to be used for creating your own annotations.
|
@Qualifier | @Named | — |
@Value | — | no equivalent |
@Required | — | no equivalent |
@Lazy | — | no equivalent |
Reference:
[1] Spring 3 and JSR-330 @Inject and @Named example
沒有留言 :
張貼留言