Search code examples
javaspring-bootspring-annotations

how to use spring annotations


I have the @Controller, @Service and @Repository classes. The application works fine, but I think I'm not using the annotations properly for the "entity" and "repository" classes.

I'm actually not using a db(not even an in-memory db) and don't intend to.

I'm currently annotating the repository with @Repository and the entities with @Service and this is my concern: am I doing this correctly?

How should I design and use the Spring annotations to wire the entity and repository classes to the service if I don't want to persist the data?

Currently it looks like this:

Service class

@Service
public class ServiceClass{
    @Autowired
    RepositoryClass repositoryClass;
    
    public ServiceClass(RepositoryClass repositoryClass) {
        this.repositoryClass = repositoryClass;
    }
}

Repository class

@Repository
public class RepositoryClass{
    @Autowired
    private Entity entity;

    public DocumentRepository(Entity entity) {
        this.entity = entity;
    }
}

Entity class

    @Service
    public class Entity {
       private Map<String, List<Integer>> entityMap;

       public Entity (Map<String, List<Integer>> entityMap) {
           this.entityMap = entityMap;
       }
    }

Solution

  • The question is: what's the role of each class here. Usually a repository is the point to access data. An entity is a data object, not a logic component, so it is usually created and managed by the repository, in this example, not Spring.

    It's hard to firmly say anything with only that code (no information about how every component is used), but I would remove the @Service from the Entity class. The other classes are ok with those annotations.