Spring @Repository best practices

前端 未结 4 587
旧巷少年郎
旧巷少年郎 2020-12-23 11:57

Context: Web application

I haven\'t used Spring before, but according to the Spring docs, all the beans are singleton, unless we declare them as p

4条回答
  •  攒了一身酷
    2020-12-23 12:15

    1. No, but it's much harder to unit test, which is what dependency injection is all about. By injecting a DAO in a service, you can easily unit-test the service by injecting a mock DAO during the test. That's not possible if the service creates its own DAO.

    2. A repository is typically completely stateless except for a thread-safe entity manager, session factory or JDBC template initialized at startup time, so being called concurrently is not a problem: it's thread-safe.

    3. There's no reason for a repository to be a prototype. Injecting a prototype DAO into a singleton service will still cause each prototype to be called concurrently anyway.

    4. There's no reason to do it.

    5. No problem: it should be thread-safe if coded correctly.

提交回复
热议问题