简体   繁体   English

SPRING BOOT 注释:是否需要

[英]SPRING BOOT annotation: are they required

Are @Component , @Service and @Repository optional in Spring Boot 2?在 Spring Boot 2 中@Component@Service@Repository是可选的吗?

Example If have a controller class called FirstController annotated with @Controller , @RestController and @RequestMapping .示例 如果有一个名为 FirstController 的 controller class 使用@Controller@RestController@RequestMapping注释。 I also have service classes called FirstService and SecondService and a repository called FirstRespository.我还有一个名为 FirstService 和 SecondService 的服务类以及一个名为 FirstRespository 的存储库。

I didn't annotate any of the class except FirstController but still my application works.除了 FirstController,我没有注释任何 class 但我的应用程序仍然有效。

Does this mean that those stereotype annotations are not required for your app to make it work?这是否意味着您的应用程序不需要那些刻板印象注释来使其工作? You just need it for convention and if you need to modify behaviour like scope etc.您只需要它来进行约定,如果您需要修改 scope 等行为。

Thanks for answering in advance.感谢您提前回答。

They are not required in order for your application to work BUT they will not be picked up by Spring on your application launch nor you will have benefits of that annotation specification它们不是您的应用程序运行所必需的,但 Spring 在您的应用程序启动时不会使用它们,您也不会从该注释规范中受益

@Component - generic stereotype for any Spring-managed component @Component - 任何 Spring 管理的组件的通用构造型

@Repository - stereotype for the persistence layer @Repository - 持久层的原型

@Service - stereotype for service layer @Service - 服务层的原型

Any code can pass when you write your Spring application, but annotation helps Spring to understand what should be created as a bean or a component and for which use.当您编写 Spring 应用程序时,任何代码都可以通过,但注释有助于 Spring 了解应该将什么创建为 bean 或组件以及用于哪些用途。

Consider this:考虑一下:

@Service
public class MyService {

private IComponent component;

@Autowired
    public MyService(IComponent component) {
        this.preparingService = preparingService;
    }
}

In order to autowire a class implementing IComponent , you need to have that class decorated with @Service or @Component in order for Spring to inject it into MyService when MyService is itself of course injected in your controller. In order to autowire a class implementing IComponent , you need to have that class decorated with @Service or @Component in order for Spring to inject it into MyService when MyService is itself of course injected in your controller.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM