1

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:

  1. Does Spring have a built in mechanism for declaring init and destroy methods on component scanned beans ?

  2. 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 !

AndrewP
  • 358
  • 2
  • 12
  • you need to include in spring config, one of the answers makes it clear, how to make annotations available in spring http://stackoverflow.com/questions/5919982/is-there-something-like-predestroy-in-the-spring-as-in-the-castle-windsor – awsome May 06 '16 at 12:45

1 Answers1

1

You can implement the InitializingBean interface. It declares afterPropertiesSet method which should do exactly what you want.

Spring Javadoc InitializingBean

J2EE - Spring equivalents

@PostConstruct - InitializingBean

@PreDestroy - DisposableBean

EDIT: Sort of misunderstood the question at first. Creating an interface for Person which extends InitializingBean or DisposableBean, implementing the declared afterPropertiesSet()/destroy() methods and changing the return type of the @Bean annotated method to the interface should do the trick.

tkralik
  • 770
  • 1
  • 8
  • 18