Spring - 使用@Service和@Repository注释同一个类

问题描述 投票:1回答:1

我不时会发现使用@Service和@Repository注释的Spring组件。像这样的东西:

@Service("carService")
@Repository
@Transactional
public class CarServiceImpl implements CarService {
    ...
}

或类似的东西:

@Transactional
@Repository
public class EventService {

    @Autowired
    private EventRepository repository;

    public EventEntity save(final EventEntity entity) {
        return repository.save(entity);
    }

    public EventEntity findOne(final String idEvent) {
        return repository.findOne(idEvent);
    }
}

做这样的事情似乎很方便,但技术上是否正确实施?

java spring hibernate spring-data-jpa
1个回答
1
投票

@Service@Repository都使用@Component进行元注释,这使得它们有资格进行扫描。从Spring 5.0开始,@Service不再添加逻辑,而@Repository可以在启用时向Spring DAO异常集添加异常转换。

但是,值得注意的是,在您提供的示例中,使用EventService而不是简单地拥有Spring Data存储库没有任何优势,并且如果存在其他逻辑,则它不能用作存储库(EventRepository依赖项)。

tl; dr:在两者上使用@Component@Service,它们之间没有显着差异(@Component因此而变得更加平常)。

© www.soinside.com 2019 - 2024. All rights reserved.