Hot questions for Using EventBus in spring

Question:

I'm following a tutorial and they @Service a class which in my mind should make it available to the whole application. Why are the @Autowire-ing the class in Application?

Application:

@Configuration
@EnableAutoConfiguration    // todo why not @SpringBootApplication
@ComponentScan
public class QuoteAppWsApplication implements CommandLineRunner {


    public static void main(String[] args) {
        SpringApplication.run(QuoteAppWsApplication.class, args);
    }


    @Autowired
    private EventBus eventBus;  //

    @Autowired // todo This is @Service...why is it be Autowired
    private NotificationConsumer notificationConsumer;

NotificationConsumer:

@Service
public class NotificationConsumer implements Consumer<Event<NotificationData>> {

    @Autowired
    private NotificationService notificationService;

    @Override
    public void accept(Event<NotificationData> notificationDataEvent) {  // .getData() belongs to Event<>
        NotificationData notificationData = notificationDataEvent.getData(); //TODO Gets data from Event

        try {
            notificationService.initiateNotification(notificationData);
        } catch (InterruptedException e) {
            // ignore
        }
    }
}

Answer:

@Service is a specialization of @Component. It is an annotation that tells Spring to include this class as a Bean in the Spring context. You can think of this as telling Spring what to pick up and put into the context during component scanning.

@Autowired is Spring's annotation to inject something from the context. You can think of this as you declaring what you want to get out of Spring. In general, you need to use this annotation on any field, constructor, or setter that you want Spring to invoke to supply you with the object that it's managing for the given type.

To answer your question, yes, you need both to declare what you want put into the context and when you want something out of the context.

Also, your first three annotations can be replaced with @SpringBootApplication. This annotation is a meta-annotation, meaning it's an annotation that it shorthand for including a series of other annotations. It's documented to include, among other things, all three of your annotations.