48

I've got problem with using @PostConstruct and@PostDestroy annotations in my project. I can't use these annotations and it looks like these doesn't exist despite the fact that I imported Java's annotations. I am using Java 11 and that is content of my build.gradle file:

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.springframework', name: 'spring-webmvc', version: '5.1.0.RELEASE'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.7'
    compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'
    provided group: 'javax.servlet', name: 'javax.servlet-api', version: '4.0.1' 
}
Prashant Gupta
  • 788
  • 8
  • 26

3 Answers3

95

Note that both @PostConstruct and @PreDestroy annotations are part of Java EE. And since Java EE has been deprecated in Java 9 and removed in Java 11 we have to add an additional dependency to use these annotations:

For Maven

<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

If using Gradle

implementation "javax.annotation:javax.annotation-api:1.3.2"

Found here: https://www.baeldung.com/spring-postconstruct-predestroy

Navid Mitchell
  • 1,276
  • 11
  • 10
2

You have only spring-webmvc, you need the rest of the spring to be able to use their annotations. Probably spring-core and spring-annotations.

Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
  • Thanks! It was the reason of my problem. –  Oct 08 '18 at 14:58
  • 3
    It doesn't make any sense that this is the solution because @PostConstruct is no spring annotation. – unwichtich Jan 24 '19 at 18:11
  • @unwichtich I disagree, it makes perfect sense. Indeed these are javax.annotation, but spring can serve these annotations, and it can be deduced from the context of this question that the OP wanted exactly this behaviour. Yes, I could do a long discussion here with the OP, but maybe He just forgeted that spring is divided and not a single jar? – Krzysztof Cichocki Jan 26 '19 at 08:02
  • Ah ok I overlooked that the OP only imported the API package and that the implementation was missing. You are right! – unwichtich Jan 28 '19 at 15:11
1

Another solution which worked for me is this. Go to https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api/1.2 and download the jar file. Then copy the the jar file to your project lib directory. Finally point the project build path, under class path to the file you pasted into your local lib folder.

Med Sep
  • 346
  • 1
  • 6