简体   繁体   中英

Autowiring multiple repositories into a single DAO in Spring - bad practice?

Let's say I have the following Spring Mongo repositories. ObjectOne, ObjectTwo and ObjectThree represent documents stored in separate collections within the same database

public interface RepositoryOne extends MongoRepository<ObjectOne, String> {
}

public interface RepositoryTwo extends MongoRepository<ObjectTwo, String> {
}

public interface RepositoryThree extends MongoRepository<ObjectThree, String> {
}

And then a single DAO class

public class ExampleDAO {
    @Autowired
    private RepositoryOne repositoryOne;

    @Autowired
    private RepositoryTwo repositoryTwo;

    @Autowired
    private RepositoryThree repositoryThree;

    //Various methods performing operations with repositoryOne
    //Various methods performing operations with repositoryTwo
    //Various methods performing operations with repositoryThree
}

Is it considered bad practice to be autowiring multiple repositories into a single DAO like above? It feels like the class may be doing too much and ideally I should have a single repository to maintain single responsibility. If it is bad practice, would a separate DAO for each repository be the way to go, or is there a Spring magic way to create a single repository that I can use to call a more specific repository?

Its a bad practice to have multiple unrelated responsibilities for a single class. If they are related consider creating a 'service' class and autowire the repositories. And also the methods in service class can abstract the methods in repositories, for example:

class ExampleService {
    @Autowired
    private RepositoryOne repositoryOne;

    @Autowired
    private RepositoryTwo repositoryTwo;

    void saveEmployee(Employee e) {
        repositoryOne.save(e);
        repositoryTwo.update(e.getEmpId);
    }
}

No one will be able to tell whether your ExampleDAO is fine to use multiple repositories or not unless looking into the actual business logic.

However, your ExampleDAO class seems like acting as a business service (look here for the subject of DAO vs Repository, they both actually different ways of implementing data access layers). In other words, you need to ensure that your ExampleDAO class handles/owns a single responsibility.

Also, the other important point is that it is a bad practice to use the field injection rather use the constructor injection. I suggest you go through here on this subject.

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