英文:
Spring - @Repository annotation in service class
问题
在CustomerServiceImpl
服务类中放置@Repository
的意义是什么?在这个例子中,这是否是一种良好的实践?据我理解,在扩展JpaRepository
的任何接口上都不需要它,因为异常转换已经包含在内。就我所知,@Repository
应该放在仓库类上。
@Repository
@Transactional(readOnly = true)
public class CustomerServiceImpl implements CustomerService {
@PersistenceContext
private EntityManager em;
@Autowired
private CustomerRepository repository;
...
}
@Transactional(readOnly = true)
public interface CustomerRepository extends JpaRepository<Customer, Long> {}
英文:
What is the point of putting @Repository in service class CustomerServiceImpl
and is it a good practice in this example, my understanding it is not needed for any interfaces that extend JpaRepository
and exception translation already included. As far as I understand @Repository "should" be on repository class?
@Repository
@Transactional(readOnly = true)
public class CustomerServiceImpl implements CustomerService {
@PersistenceContext
private EntityManager em;
@Autowired
private CustomerRepository repository;
...
}
@Transactional(readOnly = true)
public interface CustomerRepository extends JpaRepository<Customer, Long> {}
答案1
得分: 1
在给定的示例中,从技术上讲,对于CustomerServiceImpl类,@Repository注解可能并不是绝对必要的。
然而,使用@Repository注解通过实现“领域驱动设计”模式来优化“搜索”和“列出所有”操作。
示例:底层存储库可以是关系型数据库/No-sql数据库/CSV文件。在这种情况下,使用@Repository将隐藏“搜索”和“列出所有”操作的实现复杂性。
英文:
Technically, the @Repository annotation may not be absolutely necessary in the given example for the CustomerServiceImpl class.
However, the use of @Repository annotation optimizes the 'search' and 'List all' operations by implementing the 'Domain Driven Design' pattern.
Example: The underlying repository can be a Relational database / No-sql database / a CSV file. Use of @Repository will hide the implementation complexity from 'Search' and 'List all' operations in this case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论