简体   繁体   中英

How to set Init method for beans automatically created by Component Scanning in spring

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 !

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM