In explicity defined beans, it is possible to define the init and destroy methods via annotations, on the Spring configuration class:
@Configuration
@ComponentScan
public class Appconfig {
@Bean(name="Andre",initMethod="init",destroyMethod="destroy")
@Scope("singleton")
public Person person() {
Person person = new Person(1,"Andre");
person.setTaxId(5);
return person;
}
However, if the bean is created automatically by spring via component scanning, how to do it ?
I have read around that to achieve the same effect with beans created with component scanning, the init method should be annotated with @PostConstruct. However, @PostConstruct is not part of Spring, and when I use this annotation, I have the error
"PostConstruct cannot be resolved to a type".
Somehow, Eclipse seems not to know how to import this annotation automatically. After some more browsing I found out that using
import javax.annotation.PostConstruct;
works, but with an warning saying:
Access restriction: The type 'PostConstruct' is not API (restriction on required library 'C:\Program Files\Java\jre1.8.0_45\lib\rt.jar')
So I have 2 questions:
Does Spring have a built in mechanism for declaring init and destroy methods on component scanned beans ?
Why do I have the error: Access restriction: The type 'PostConstruct' is not API (restriction on required library 'C:\Program Files\Java\jre1.8.0_45\lib\rt.jar') when using @PostConstruct ?
Thanks in advance !