简体   繁体   中英

Should I use the @Repository Spring annotation for a bean responsible to persist data on the filesystem

I have three layers in my application:

  • REST interface (JBOSS RestEasy)
  • Service layer (Spring Services)
  • Persistence layer (Spring beans)

In the persistence layer I will implement two classes (which implement the same interface): one will be a MemoryStore and the other one FileSystemStore .

Should these implementation be annotated by @Repository ?

The two classes will not have any Database access. It can comes later an implementation to a DatabaseStore but it is not the case now.

More generally, is the annotation @Repository must be used for any persistence Bean or only for those who access a Database?

The class javadoc says:

A class thus annotated [with @Respository] is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.

I believe that you must annotate your class with @Repository if you need special exception translation (from JDBC, Hibernate or some other) or your own technology (but that means that you have to extend spring to know about this) otherwise, just annotate with @Component.

In your specific case, I think it is correct to annotate with @Repository because your interface is designed for data persistence.

This is not just about the @Repository annotation, but about what stereotype the class is. If its a repository class, then it will likely be named XxxxxRepository and have the @Repository annotation.

Repositories can have different implementations, eg:

  • JpaRepository
  • MongoDbRepository

You could add your file system repo as another implementation. This seems to fit with the repo pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM