Spring – 在服务类中使用 @Repository 注解

huangapple go评论58阅读模式
英文:

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&lt;Customer, Long&gt; {}

答案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.

huangapple
  • 本文由 发表于 2020年8月20日 03:51:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63494043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定