= Event Subscribers

:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
:page-partial:


Domain services acting as xref:events.adoc[event] subscribers can subscribe to xref:userguide:ROOT:events.adoc#lifecycle-events[lifecycle] events, influencing the rendering and behaviour of other objects.

Behind the scenes this uses Spring's (in-memory) link:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#context-functionality-events-annotation[event bus], and so the way to subscribe is using Spring's `@EventListener` annotation.

[source,java]
----
import org.springframework.context.event.EventListener;
// ...

@Service                                                        // <.>
@RequiredArgsConstructor(onConstructor_ = {@Inject} )
public class OnCustomerDeletedCascadeDeleteOrders {

    private final OrderRepository orderRepository;

    @EventListener(Customer.DeletedEvent.class)                 // <.>
    public void on(final Customer.DeletedEvent ev) {            // <.>
        Customer customer = ev.getSource();
        orderRepository.delete(customer);
    }
}
----
<.> use Spring Framework's link:https://javadoc.io/doc/org.springframework/spring-context/latest/org/springframework/context/event/EventListener.html[@EventListener]
<.> the parameter type of the method corresponds to the event emitted on the event bus.
The actual method name does not matter (though it must have `public` visibility).
