@PostConstruct and @PreDestroy annotations do not work

Tags: , ,



I have TennisCoach class:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class TennisCoach implements Coach {
    @Autowired
    @Qualifier("randomFortuneService")
    private FortuneService fortuneService;

    public TennisCoach() {
        System.out.println("Inside default constructor");
    }

    @PostConstruct
    public void doMyStartupStuff() {
        System.out.println("Inside postconstructor");
    }

    @PreDestroy
    public void doMyFinalStuff() {
        System.out.println("Inside predestroyer");
    }

    @Override
    public String getDailyFortune() {
        return fortuneService.getFortune();
    }

    @Override
    public String getDailyWorkout() {
        return "Practice your backhand volley";
    }
}

And such main class:

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AnnotationBeanScopeDemoApp {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        Coach theCoach = context.getBean("tennisCoach", Coach.class);

        System.out.println(theCoach.getDailyFortune());
        System.out.println(theCoach.getDailyWorkout());

        context.close();
    }
}

Expected output is:

Inside default constructor

Inside postconstructor

DailyFortune

Practice your backhand volley

Inside predestroyer

But I get this:

Inside default constructor

DailyFortune

Practice your backhand volley

It seems like @PostContruct and @PreDestroy annotations do not work correctly. I cannot find the reason of my problem.

Answer

If you use java 9+ then add dependency javax.annotation:javax.annotation-api (or use java 8).

Or use spring-boot 2 if you using spring-boot 1.



Source: stackoverflow