如果一个 class 已经是@Service,那么它是否需要在 Spring Application class 中被@Autowired?

If a class is already @Service, then does it need to be @Autowired in Spring Application class?

我正在学习一个教程,他们@Service a class 在我看来应该使它对整个应用程序可用。 为什么 @Autowire-ing 是应用程序中的 class?

申请:

@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;

通知消费者:

@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
        }
    }
}

@Service@Component 的特化。它是一个注释,告诉 Spring 将此 class 作为 Bean 包含在 Spring 上下文中。您可以将其视为告诉 Spring 在组件扫描期间要选取什么并将其放入上下文中。

@Autowired 是 Spring 的注解,用于从上下文中注入一些东西。您可以在声明要从 Spring 中得到什么时考虑这一点。通常,您需要在您希望 Spring 调用的任何字段、构造函数或 setter 上使用此注释,以便为您提供它为给定类型管理的对象。

要回答您的问题,是的,您既需要声明要放入上下文中的内容,也需要声明何时需要脱离上下文的内容。

此外,您的前三个注释可以替换为@SpringBootApplication。此注释是一个元注释,这意味着它是一个注释,它 shorthand 用于包含一系列其他注释。据记录,除其他事项外,还包括您的所有三个注释。