In this tutorial, we will explore how to use the initMethod
and destroyMethod
attributes of the @Bean
annotation in Spring to specify initialization and destruction methods. These attributes allow us to define
methods that will be called after bean properties have been set and before the bean is destroyed, without
implementing the InitializingBean
or DisposableBean
interfaces.
The @Bean
annotation in Spring provides a way to declare a bean along with its initialization
and destruction
methods. This is useful for performing custom logic during bean initialization and cleanup.
Create a class MyBean
with custom initialization and destruction methods.
package net.javaguides.spring.lifecycle;
public class MyBean {
public void customInit() {
// Custom initialization logic
System.out.println("MyBean: customInit method called");
}
public void customDestroy() {
// Custom cleanup logic
System.out.println("MyBean: customDestroy method called");
}
}
Create a configuration class to define the bean using the @Bean
annotation with
initMethod
and destroyMethod
attributes.
package net.javaguides.spring.lifecycle;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean(initMethod = "customInit", destroyMethod = "customDestroy")
public MyBean myBean() {
return new MyBean();
}
}
Create a main class to run your Spring Boot application.
package net.javaguides.spring.lifecycle;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@SpringBootApplication
public class SpringLifecycleApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
context.close();
}
}
Run the SpringLifecycleApplication
class as a Java application. You should see the following
output in the console:
MyBean: customInit method called
When you shut down the application (e.g., by stopping the Spring Boot application in your IDE), you should see the following output in the console:
MyBean: customDestroy method called
customInit
and
customDestroy
.
@Bean
annotation with initMethod
and destroyMethod
attributes
to specify the initialization and destruction methods.initMethod
and destroyMethod
attributes are useful,
consider using
@PostConstruct
and @PreDestroy
annotations for a more concise and modern
approach.
In this tutorial, we have learned how to use the initMethod
and destroyMethod
attributes of the @Bean
annotation in Spring for managing bean lifecycle events. We have seen how to create a simple Spring Boot
application to demonstrate their usage and discussed best practices for their use.
This approach ensures that your beans are properly initialized and cleaned up, making your application more robust and maintainable.