2013年6月16日 星期日

[筆記] Spring Annotation 的意義



在很多網路上的範例程式,常常都會看許多相同的場景卻用到到各種不同的寫法,最常見的就是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:
也就是說@Autowire是spring原本在使用的Annotaion,而@Resource和@Inject 是後來定的業界標準,新版的Spring也都可以相容,如果沒有打算使用其他Ioc的framework如Google-guice,那還是仍然可以使用Spring原生的annotation。

詳細的比較可以參考Spring 3.1 - beans-standard-annotations-limitations

Table 4.6. Spring annotations vs. standard annotations
Springjavax.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
@Valueno equivalent
@Requiredno equivalent
@Lazyno equivalent



Reference:
[1] Spring 3 and JSR-330 @Inject and @Named example


張貼留言