@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?

换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?

或者注释是否也会影响类的行为和功能?


当前回答

即使它的行为相同,但这利用了应用程序的许多软件开发原则,也很少有这样的例子:

- Single Responsibility
- Open Closed Principal 

其他回答

@存储库@Service和@Controller用作@Component的专用化,以便更具体地使用。在此基础上,您可以将@Service替换为@Component,但在这种情况下,您会失去专用化。

1. **@Repository**   - Automatic exception translation in your persistence layer.
2. **@Service**      - It indicates that the annotated class is providing a business service to other layers within the application.

我们可以根据java标准回答这个问题

参考JSR-330,它现在被spring支持,您只能使用@Named来定义bean(不知何故,@Named=@Component)。因此,根据这个标准,似乎没有必要为类别bean定义原型(如@Repository、@Service、@Controller)。

但是spring用户在这些不同的注释中有不同的特定用途,例如:

帮助开发人员为胜任者定义更好的类别。这种分类在某些情况下可能会有所帮助。(例如,当您使用面向方面的时,这些可能是切入点的好候选)@存储库注释将为bean添加一些功能(为bean持久层添加一些自动异常转换)。如果您使用的是springMVC,则@RequestMapping只能添加到由@Controller注释的类中。

@Component
@Controller
@Repository
@Service
@RestController

这些都是StereoType注释。这对于在ioc容器中将我们的类制作为springbean非常有用,

@组件在配置类中充当@Bean注释,在spring上下文中注册Bean。它也是@Service、@Repository和@Controller注释的父级。

@服务,扩展了@Component注释,只有命名差异。

@Repository-扩展@Component注释并将所有数据库异常转换为DataAccessException。

@控制器-在MVC模式中充当控制器。分派器将扫描这些带注释的类以查找映射方法,检测@RequestMapping注释。

即使我们交换@Component或@Repository或@service

它的行为是一样的,但一个方面是,如果我们使用component或@service,它们将无法捕获与DAO相关的特定异常,而不是Repository