An annotated version of ApplicationListener <ContextClosedEvent> and similar interfaces

You can use the following code to do some events based on when your web service is disconnected (or updated / started).

public class APIService implements ApplicationListener<ContextClosedEvent>
{
    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        //Do shutdown work.
    }
}

I was told that there is an annotation-based method that does not require the implementation of this interface. In particular, you should be able to define a function with any name you like and annotate it so that it runs when the service starts or shuts down.

I am having trouble finding links to this in my spring book or through google. Can someone give an example of how to make the above code only through annotations?

+2
2

Spring 4+, , .

@Component // defaults to eager initialization
class Setup {
    @Autowired
    private ApplicationContext context;

    @PostConstruct
    public void anyNameYouWant() {
        System.out.println("starting");
    }

    @PreDestroy
    public void hereToo() {
        System.out.println("closing");
    }
}

ContextClosedEvent ApplicationContextEvent s.

+5

@EventListener Spring 4.2

0

Source: https://habr.com/ru/post/1533454/


All Articles