简体   繁体   中英

SPRING BOOT annotation: are they required

Are @Component , @Service and @Repository optional in Spring Boot 2?

Example If have a controller class called FirstController annotated with @Controller , @RestController and @RequestMapping . I also have service classes called FirstService and SecondService and a repository called FirstRespository.

I didn't annotate any of the class except FirstController but still my application works.

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.

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

@Component - generic stereotype for any Spring-managed component

@Repository - stereotype for the persistence layer

@Service - stereotype for service layer

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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