@Service vs @Component在春季

时间:2019-05-22 15:18:20

标签: spring spring-boot

我了解@Component和@ Controller,@ Component和@Repository之间的区别,但是无法找到与@Component相比我们在@Service中获得的其他功能。

1 个答案:

答案 0 :(得分:3)

enter image description here

我们可以为每个bean直接使用@Component,但是为了更好地理解和维护大型应用程序,我们使用@Controller, @Service, @Repository

@Component: generic stereotype for any Spring-managed component 
@Service: stereotype for service layer

@Component

@ Controller,@ Service和@Repository批注的定义,它们表明@Service是@Component的特殊类型。特殊类型的注释也会被扫描,因为它们本身都带有@Component注释,这意味着它们也是@Component。如果我们定义自己的自定义注释并用@Component进行注释,则也会使用<context:component-scan>

对其进行扫描
@Component
public @interface Service {
    ….
}

@Component
public @interface Repository {
    ….
}

@Component
public @interface Controller {
    …
}

@服务

@Service bean在存储库层中保存业务逻辑和调用方法。