Spring bean lifecycle: from constructor to destroy

Spring creates every bean in a fixed sequence of steps, and it gives you several places to run your own code along the way. This page traces that sequence on a real context, then shows what happens when an init method fails, which beans are never destroyed, the order beans shut down in, and the traps that make a callback silently not run.

Contents

What the bean lifecycle is

A Spring bean is an object whose creation and destruction the container controls. You never call new on it yourself. The container reads a bean definition, creates the object, fills in its dependencies, gives it a chance to prepare itself, hands it out, and finally lets it release what it holds when the application stops. That sequence is the bean lifecycle.

For a singleton bean, the default, the sequence runs like this:

  1. Instantiation: the container calls the constructor (or the @Bean factory method). Constructor arguments are the first dependencies injected.
  2. Property population: @Autowired fields and setter methods are filled in.
  3. Aware callbacks: if the bean implements BeanNameAware, BeanFactoryAware or ApplicationContextAware, it receives its name, the bean factory or the context.
  4. Before-initialization post-processing: every BeanPostProcessor sees the bean through postProcessBeforeInitialization.
  5. Initialization: @PostConstruct methods, then InitializingBean.afterPropertiesSet(), then a custom init method.
  6. After-initialization post-processing: postProcessAfterInitialization runs. This is where Spring wraps the bean in a proxy for @Transactional, @Async or other aspects, so the object other beans receive may be a proxy, not your class.
  7. In use: the bean serves the application until the context closes.
  8. Destruction: @PreDestroy methods, then DisposableBean.destroy(), then a custom destroy method.

All of this happens inside refresh(), which new AnnotationConfigApplicationContext(Config.class) calls for you. Singletons are created eagerly at that point, so a failure in any init callback stops the application from starting. Destruction happens in close().

Ways to hook into the lifecycle
MechanismDefined byRunsBest for
@PostConstruct, @PreDestroyJakarta Annotations (jakarta.annotation)Init and destroy, first in each groupClasses you write; the usual choice
InitializingBean, DisposableBeanSpring (org.springframework.beans.factory)Init and destroy, secondFramework code that should not depend on annotation processing
@Bean(initMethod, destroyMethod)Spring Java configurationInit and destroy, thirdThird-party classes you cannot annotate
Inferred destroy methodSpring, for @Bean methodsDestroy, when no destroy method is namedAnything with a public close() or shutdown()
BeanPostProcessorSpringAround the init callbacks of every beanCross-cutting changes to many beans, such as proxies
SmartLifecycleSpringstart() after all singletons exist, stop() before any is destroyedBackground work: consumers, schedulers, servers
SmartInitializingSingletonSpring, since 4.1Once, after all singletons are createdWork that needs every other bean ready

Every example on this page is a complete program on Spring Framework 7.0 without Spring Boot. Boot uses the same container, so the callbacks run identically there.

Every callback, traced in order

This program gives one bean every init and destroy mechanism at once, plus a BeanPostProcessor that reports when it sees that bean. Numbering each step makes the order visible without reading Spring's source:

Java
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class LifecycleTrace {

    static int step = 0;

    static void log(String message) {
        System.out.printf("%2d. %s%n", ++step, message);
    }

    @Configuration
    static class Config {
        @Bean
        static BeanPostProcessor tracer() {
            return new BeanPostProcessor() {
                @Override
                public Object postProcessBeforeInitialization(Object bean, String name) {
                    if (bean instanceof PriceCache) {
                        log("BeanPostProcessor.postProcessBeforeInitialization");
                    }
                    return bean;
                }

                @Override
                public Object postProcessAfterInitialization(Object bean, String name) {
                    if (bean instanceof PriceCache) {
                        log("BeanPostProcessor.postProcessAfterInitialization");
                    }
                    return bean;
                }
            };
        }

        @Bean
        PriceFeed priceFeed() {
            return new PriceFeed();
        }

        @Bean(initMethod = "customInit", destroyMethod = "customDestroy")
        PriceCache priceCache() {
            return new PriceCache();
        }
    }

    static class PriceFeed {
    }

    static class PriceCache implements BeanNameAware, ApplicationContextAware,
            InitializingBean, DisposableBean {

        PriceCache() {
            log("constructor");
        }

        @Autowired
        void setFeed(PriceFeed feed) {
            log("@Autowired setter: feed injected");
        }

        @Override
        public void setBeanName(String name) {
            log("BeanNameAware.setBeanName(\"" + name + "\")");
        }

        @Override
        public void setApplicationContext(ApplicationContext context) {
            log("ApplicationContextAware.setApplicationContext");
        }

        @PostConstruct
        void postConstruct() {
            log("@PostConstruct");
        }

        @Override
        public void afterPropertiesSet() {
            log("InitializingBean.afterPropertiesSet");
        }

        void customInit() {
            log("@Bean(initMethod) customInit");
        }

        @PreDestroy
        void preDestroy() {
            log("@PreDestroy");
        }

        @Override
        public void destroy() {
            log("DisposableBean.destroy");
        }

        void customDestroy() {
            log("@Bean(destroyMethod) customDestroy");
        }
    }

    public static void main(String[] args) {
        System.out.println("Starting the context:");
        var context = new AnnotationConfigApplicationContext(Config.class);
        log("context ready, bean in use: " + context.getBean(PriceCache.class).getClass()
                .getSimpleName());
        System.out.println("Closing the context:");
        context.close();
    }
}
Output
Starting the context:
 1. constructor
 2. @Autowired setter: feed injected
 3. BeanNameAware.setBeanName("priceCache")
 4. ApplicationContextAware.setApplicationContext
 5. BeanPostProcessor.postProcessBeforeInitialization
 6. @PostConstruct
 7. InitializingBean.afterPropertiesSet
 8. @Bean(initMethod) customInit
 9. BeanPostProcessor.postProcessAfterInitialization
10. context ready, bean in use: PriceCache
Closing the context:
11. @PreDestroy
12. DisposableBean.destroy
13. @Bean(destroyMethod) customDestroy
  • Step 1 is the constructor and step 2 the @Autowired setter. Dependencies that are not constructor arguments arrive only after the object exists, which is why a constructor cannot use them.
  • Steps 3 and 4 are the Aware callbacks. The bean learns that its name is priceCache, taken from the @Bean method name.
  • Step 5 is the post-processor's before hook, and steps 6 to 8 are the three init mechanisms, in the documented order: annotation, interface, custom method. @PostConstruct is itself run by a post-processor, CommonAnnotationBeanPostProcessor. Spring registers its own internal post-processors at the end of the chain, so yours sees the bean first.
  • Step 9, the after hook, is the last step before the bean is ready. A post-processor that returns a different object here, such as a proxy, replaces the bean for everyone who injects it.
  • Steps 11 to 13 are the destroy callbacks, again annotation, interface, custom method. They run only because main calls context.close().

Using all three mechanisms on one bean is for the demonstration only. Pick one per bean. If two mechanisms name the same method, for example initMethod = "afterPropertiesSet", Spring calls it once.

@PostConstruct and @PreDestroy

@PostConstruct marks a method to run once the bean is fully injected, and @PreDestroy one to run before the bean is discarded. They are the recommended callbacks because they do not tie the class to a Spring interface. The method may have any visibility, must take no arguments, and is usually void.

Init callbacks run while the context is starting, so an exception in one stops the startup. Here a connection pool starts first, then a rate table fails to load its file:

Java
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class InitFailure {

    @Configuration
    static class Config {
        @Bean
        ConnectionPool connectionPool() {
            return new ConnectionPool();
        }

        @Bean
        RateTable rateTable(ConnectionPool pool) {
            return new RateTable();
        }
    }

    static class ConnectionPool {
        @PostConstruct
        void open() {
            System.out.println("ConnectionPool: opened 5 connections");
        }

        @PreDestroy
        void close() {
            System.out.println("ConnectionPool: closed 5 connections");
        }
    }

    static class RateTable {
        @PostConstruct
        void load() {
            System.out.println("RateTable: loading rates.csv");
            throw new IllegalStateException("rates.csv not found");
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            System.out.println("never printed: " + context.getBeanDefinitionCount());
        } catch (BeanCreationException e) {
            System.out.println("Startup failed with " + e.getClass().getSimpleName());
            System.out.println("  bean   : " + e.getBeanName());
            System.out.println("  message: " + e.getMessage());
            System.out.println("  cause  : " + e.getMostSpecificCause());
        }
    }
}
Output
ConnectionPool: opened 5 connections
RateTable: loading rates.csv
ConnectionPool: closed 5 connections
Startup failed with BeanCreationException
  bean   : rateTable
  message: Error creating bean with name 'rateTable': Invocation of init method failed
  cause  : java.lang.IllegalStateException: rates.csv not found
WARNING:Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'rateTable': Invocation of init method failed
  • ConnectionPool opened first, because rateTable depends on it.
  • RateTable.load() threw, and the context constructor threw BeanCreationException instead of returning. Its message names the bean, rateTable, and says an init method failed; getMostSpecificCause() returns the original IllegalStateException.
  • Before giving up, Spring destroyed the singletons it had already created, so the pool printed closed 5 connections. A failed startup does not leak resources that were set up with proper destroy callbacks.
  • The WARNING line at the end is Spring's own log record of the cancelled refresh. It goes to standard error, so it appears after the standard output here.

The annotations come from the jakarta.annotation-api jar. Spring Boot's starters bring it in; with plain Spring Framework you add it yourself, or the annotations will not compile. Spring Framework 6 moved from javax.annotation to jakarta.annotation but still recognized both. Spring Framework 7 recognizes only the jakarta versions, as the traps section below shows running.

@Bean init and destroy methods, and inferred close()

For a class you cannot change, such as a client from a library, name its methods on the @Bean annotation: @Bean(initMethod = "start", destroyMethod = "stop"). Spring also guesses a destroy method when you name none, which is convenient for connection pools and clients, and surprising when it closes an object you meant to keep open. This program registers five beans with different close methods:

Java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class DestroyInference {

    static class FileArchive {
        public void close() {
            System.out.println("  FileArchive.close()");
        }
    }

    static class MetricsReporter {
        public void shutdown() {
            System.out.println("  MetricsReporter.shutdown()");
        }
    }

    static class SharedClient implements AutoCloseable {
        @Override
        public void close() {
            System.out.println("  SharedClient.close()");
        }
    }

    static class ScannedResource implements AutoCloseable {
        @Override
        public void close() {
            System.out.println("  ScannedResource.close()");
        }
    }

    static class PlainComponent {
        public void close() {
            System.out.println("  PlainComponent.close()");
        }
    }

    @Configuration
    static class Config {
        @Bean   // no destroyMethod given: Spring infers close()
        FileArchive fileArchive() {
            return new FileArchive();
        }

        @Bean   // no close(), so Spring infers shutdown()
        MetricsReporter metricsReporter() {
            return new MetricsReporter();
        }

        @Bean(destroyMethod = "")   // inference switched off
        SharedClient sharedClient() {
            return new SharedClient();
        }
    }

    public static void main(String[] args) {
        var context = new AnnotationConfigApplicationContext();
        context.register(Config.class, ScannedResource.class, PlainComponent.class);
        context.refresh();
        System.out.println("Closing the context:");
        context.close();
    }
}
Output
Closing the context:
  MetricsReporter.shutdown()
  FileArchive.close()
  ScannedResource.close()
  • FileArchive has a public close() and implements no interface, yet Spring called it. For @Bean methods the default destroyMethod is the special value "(inferred)", which looks for a public close() or shutdown().
  • MetricsReporter has no close(), so Spring fell back to shutdown().
  • SharedClient implements AutoCloseable, but destroyMethod = "" turned inference off, and nothing was printed for it. Use this for an object whose life is managed elsewhere, such as a client that another library also holds.
  • ScannedResource was registered as a component class, not through a @Bean method. Spring still called its close(), because it implements AutoCloseable.
  • PlainComponent has a public close() too, but it is a component class with no interface, and inference applies only to @Bean methods. It was not closed.

The beans were destroyed in the reverse order of their creation. ScannedResource was created first, so it was destroyed last.

Prototype beans are never destroyed

A prototype bean is created fresh for every request, and the container hands it over and forgets it. It still gets its init callbacks, but the container keeps no reference to call destroy callbacks later. This program asks for three report writers, destroys one by hand, then closes the context:

Java
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

public class PrototypeDestroy {

    static int created = 0;

    @Component
    @Scope("prototype")
    static class ReportWriter {
        private final int id = ++created;

        @PostConstruct
        void open() {
            System.out.println("  @PostConstruct on writer " + id);
        }

        @PreDestroy
        void close() {
            System.out.println("  @PreDestroy on writer " + id);
        }
    }

    public static void main(String[] args) {
        var context = new AnnotationConfigApplicationContext(ReportWriter.class);
        System.out.println("Asking for three writers:");
        ReportWriter first = context.getBean(ReportWriter.class);
        context.getBean(ReportWriter.class);
        context.getBean(ReportWriter.class);
        System.out.println("Destroying writer 1 by hand:");
        context.getBeanFactory().destroyBean(first);
        System.out.println("Closing the context:");
        context.close();
        System.out.println("Context closed");
    }
}
Output
Asking for three writers:
  @PostConstruct on writer 1
  @PostConstruct on writer 2
  @PostConstruct on writer 3
Destroying writer 1 by hand:
  @PreDestroy on writer 1
Closing the context:
Context closed
  • Each getBean call created a new writer, and each one ran @PostConstruct: writers 1, 2 and 3.
  • getBeanFactory().destroyBean(first) ran the destroy callbacks for writer 1. That is the way to clean up a prototype when you know you are done with it.
  • Closing the context printed nothing. Writers 2 and 3 never had @PreDestroy called. If they had held a file handle or a thread, it would have leaked.

Give prototype beans nothing that needs closing, or have the code that asks for them close them, for example by making the bean AutoCloseable and using try-with-resources. The bean scopes page covers prototype and the other scopes in detail.

Startup and shutdown order, and SmartLifecycle

Spring creates beans in dependency order and destroys them in the reverse order, so a bean can always use its dependencies in its own destroy callback. Some beans need a further step: a message consumer should start polling only once everything is ready, and stop polling before the database goes away. SmartLifecycle adds start() and stop() for that. The configuration below declares the beans in the wrong order on purpose:

Java
import jakarta.annotation.PreDestroy;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

public class ShutdownOrder {

    static class Database {
        Database() {
            System.out.println("  create  Database");
        }

        @PreDestroy
        void close() {
            System.out.println("  destroy Database");
        }
    }

    static class OrderRepository {
        OrderRepository(Database db) {
            System.out.println("  create  OrderRepository");
        }

        @PreDestroy
        void close() {
            System.out.println("  destroy OrderRepository");
        }
    }

    static class QueueConsumer implements SmartLifecycle {
        private boolean running;

        QueueConsumer(OrderRepository repository) {
            System.out.println("  create  QueueConsumer");
        }

        @Override
        public void start() {
            running = true;
            System.out.println("  start   QueueConsumer (polling the queue)");
        }

        @Override
        public void stop() {
            running = false;
            System.out.println("  stop    QueueConsumer (no new messages taken)");
        }

        @Override
        public boolean isRunning() {
            return running;
        }

        @PreDestroy
        void close() {
            System.out.println("  destroy QueueConsumer");
        }
    }

    @Configuration
    static class Config {
        @Bean
        QueueConsumer queueConsumer(OrderRepository repository) {
            return new QueueConsumer(repository);
        }

        @Bean
        OrderRepository orderRepository(Database db) {
            return new OrderRepository(db);
        }

        @Bean
        Database database() {
            return new Database();
        }

        @EventListener
        void onRefresh(ContextRefreshedEvent event) {
            System.out.println("  event   ContextRefreshedEvent");
        }

        @EventListener
        void onClose(ContextClosedEvent event) {
            System.out.println("  event   ContextClosedEvent");
        }
    }

    public static void main(String[] args) {
        System.out.println("refresh():");
        var context = new AnnotationConfigApplicationContext(Config.class);
        System.out.println("close():");
        context.close();
    }
}
Output
refresh():
  create  Database
  create  OrderRepository
  create  QueueConsumer
  start   QueueConsumer (polling the queue)
  event   ContextRefreshedEvent
close():
  event   ContextClosedEvent
  stop    QueueConsumer (no new messages taken)
  destroy QueueConsumer
  destroy OrderRepository
  destroy Database
  • QueueConsumer is declared first, but Database was created first and OrderRepository second. Spring follows the dependencies, not the order of the @Bean methods.
  • start() ran after all three beans existed, and before ContextRefreshedEvent was published. A SmartLifecycle bean starts automatically during refresh(), because its isAutoStartup() returns true by default.
  • On close(), the ContextClosedEvent came first, then stop(), and only then the destroy callbacks. The consumer stopped taking messages while the repository and database were still alive.
  • The destroy callbacks ran in the reverse of the creation order: consumer, repository, database.

With several SmartLifecycle beans, getPhase() orders them: the lowest phase starts first and stops last. The default is SmartLifecycle.DEFAULT_PHASE, which is Integer.MAX_VALUE, and plain Lifecycle beans have phase 0. During shutdown, Spring waits up to 30 seconds per phase for asynchronous stops, the default of DefaultLifecycleProcessor.

Destroy callbacks run only when something calls close(). In a standalone program, call context.registerShutdownHook() so that the JVM closes the context on exit or on Ctrl+C. Spring Boot registers this hook for you, and web servers close their context when the application is undeployed.

Callbacks that silently do not run

The worst lifecycle bugs produce no error: the callback simply does not happen, or happens without what you expected. This program shows three of them in one context:

Java
import jakarta.annotation.PostConstruct;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class LifecycleTraps {

    static class Clock {
    }

    static class FieldInjected {
        @Autowired
        private Clock clock;

        FieldInjected() {
            System.out.println("  in the constructor : clock = " + clock);
        }

        @PostConstruct
        void init() {
            System.out.println("  in @PostConstruct  : clock = "
                    + clock.getClass().getSimpleName());
        }
    }

    static class LegacyAnnotations {
        // Both annotations are written out in full, so the two packages are easy to tell apart
        @javax.annotation.PostConstruct
        void javaxInit() {
            System.out.println("  javax.annotation.PostConstruct ran");
        }

        @jakarta.annotation.PostConstruct
        void jakartaInit() {
            System.out.println("  jakarta.annotation.PostConstruct ran");
        }
    }

    static class CacheLoader {
        @PostConstruct
        void init() {
            System.out.print("  this.load() from @PostConstruct        : ");
            load();
        }

        @Transactional(readOnly = true)
        public void load() {
            System.out.println("transaction active = "
                    + TransactionSynchronizationManager.isActualTransactionActive());
        }
    }

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            return new DriverManagerDataSource("jdbc:h2:mem:traps");
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        Clock clock() {
            return new Clock();
        }

        @Bean
        FieldInjected fieldInjected() {
            return new FieldInjected();
        }

        @Bean
        LegacyAnnotations legacyAnnotations() {
            return new LegacyAnnotations();
        }

        @Bean
        CacheLoader cacheLoader() {
            return new CacheLoader();
        }

        @EventListener
        void onRefresh(ContextRefreshedEvent event) {
            System.out.print("  proxy.load() from ContextRefreshedEvent: ");
            event.getApplicationContext().getBean(CacheLoader.class).load();
        }
    }

    public static void main(String[] args) {
        System.out.println("Starting the context:");
        var context = new AnnotationConfigApplicationContext(Config.class);
        System.out.println("Context started, active = " + context.isActive());
        context.close();
    }
}
Output
Starting the context:
  in the constructor : clock = null
  in @PostConstruct  : clock = Clock
  jakarta.annotation.PostConstruct ran
  this.load() from @PostConstruct        : transaction active = false
  proxy.load() from ContextRefreshedEvent: transaction active = true
Context started, active = true
  • Field injection in the constructor: the constructor of FieldInjected saw clock = null, because Spring fills @Autowired fields only after the object exists. In @PostConstruct the field was set. Use constructor injection, or move the code into @PostConstruct.
  • The javax annotation: LegacyAnnotations has two init methods, and only jakarta.annotation.PostConstruct ran. The method marked with javax.annotation.PostConstruct compiled, because an old javax annotation jar was on the classpath, and Spring Framework 7 ignored it without a warning. Search for javax.annotation when you upgrade.
  • Transactions in @PostConstruct: this.load() from @PostConstruct ran with transaction active = false, although load() is @Transactional. The call went to the object itself, not to the proxy, which is created only after the init callbacks. Called through the proxy from a ContextRefreshedEvent listener, the same method had a transaction.

The general rule: @PostConstruct is for preparing the bean itself, from its own fields. Work that needs proxies or other beans to be fully ready belongs in an ApplicationListener for ContextRefreshedEvent, a SmartInitializingSingleton, a SmartLifecycle, or, in Spring Boot, an ApplicationRunner. The @Transactional page explains why calls on this skip the proxy, and Spring events covers the listeners.

Other things to know

  • Lazy beans: a bean marked @Lazy is created, and its @PostConstruct run, on first use instead of during startup. That makes startup faster but moves init failures to the first request.
  • Long init work: a slow @PostConstruct, such as loading a large cache, delays startup for the whole application, because by default singletons are created one at a time on the startup thread. Spring Framework 6.2 added @Bean(bootstrap = Bean.Bootstrap.BACKGROUND) to create chosen beans on a background thread; without an Executor bean named bootstrapExecutor, Spring logs a message and creates them on the startup thread anyway.
  • BeanPostProcessor beans: declare @Bean methods that return a BeanPostProcessor as static, as the trace program does. Post-processors are created before other beans, and a non-static method forces its whole configuration class to be created early.
  • Exceptions in destroy callbacks: Spring logs an exception thrown from a destroy method and continues with the next bean, so one failing close() does not stop the others.
  • Checked exceptions: init and destroy methods may declare throws Exception. Spring wraps a failure in BeanCreationException at startup.

Choosing a callback

Which lifecycle hook to use
You need toUse
Check or prepare a bean you wrote, once it is injected@PostConstruct
Release resources of a bean you wrote@PreDestroy, or implement AutoCloseable
Start or stop a library class you cannot annotate@Bean(initMethod = ..., destroyMethod = ...)
Keep Spring from closing a shared object@Bean(destroyMethod = "")
Run background work only while the whole application is upSmartLifecycle, with a phase if order matters
Call transactional or other proxied methods at startupA ContextRefreshedEvent listener, or ApplicationRunner in Spring Boot
Change or wrap many beans as they are createdA static BeanPostProcessor bean
Clean up a prototype beanClose it yourself, or call destroyBean

Keep each bean to one init and one destroy mechanism, prefer constructor injection so the object is complete when it is built, and make sure something calls close() on the context. The dependency injection page explains constructor injection, and Java configuration covers @Bean methods.