简体   繁体   中英

Usage of @Bean annotation

Suppose I have the following Spring context configuration:

@Configuration
public class Configuration {

    @Bean
    public A a() {
        return new A(b());
    }

    public B b() {
        return new B();
    }
}

Should one annotate b() with @Bean if the only place where B instance needed is within a() for A instance construction?

If B is a plan Java class (no Spring annotations) then no, You can use current configuration. As this is a private member of A class.

But if you have methods that need to be managed by spring (inside B class), like @PostConstruct or @PreDestroy, than you should make a Bean out of B class:

@Bean
public A a(B b) {
    return new A(b);
}
@Bean
public B b() {
    return new B();
}

Such cases are:

  • resource to be closed on shutdown/close
  • executors to be closed on shutdown
  • jdbc connections
  • etc

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