WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Framework · Intermediate · question 24 of 100

What is the purpose of the init-method and destroy-method attributes in Spring Bean configuration?

📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

The ‘init-method‘ and ‘destroy-method‘ attributes in Spring Bean configuration are used for specifying the methods that should be called when a bean is initialized or destroyed respectively.

The ‘init-method‘ attribute is used to specify the name of the method that should be called when a bean is initialized. This method is typically used to perform any initialization logic or setup that is required for the bean. The method should have a void return type and no arguments. Here’s an example of how to specify an ‘init-method‘ in Spring XML configuration:

<bean id="myBean" class="com.example.MyBean" init-method="init"/>

In the above example, the method ‘init()‘ of the ‘MyBean‘ class will be called when the ‘myBean‘ bean is initialized.

The ‘destroy-method‘ attribute is used to specify the name of the method that should be called when a bean is destroyed. This method is typically used to perform any cleanup logic or teardown that is required for the bean. The method should have a void return type and no arguments. Here’s an example of how to specify a ‘destroy-method‘ in Spring XML configuration:

<bean id="myBean" class="com.example.MyBean" destroy-method="cleanup"/>

In the above example, the method ‘cleanup()‘ of the ‘MyBean‘ class will be called when the ‘myBean‘ bean is destroyed.

It’s important to note that the ‘init-method‘ and ‘destroy-method‘ attributes are optional, and not all beans will require them. Additionally, these methods can be defined in the bean class itself instead of being specified in the XML configuration. If a bean defines both an ‘init()‘ and ‘@PostConstruct‘ method, Spring will call both methods during initialization, but only one ‘destroy()‘ or ‘@PreDestroy‘ method during destruction.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Framework interview — then scores it.
📞 Practice Spring Framework — free 15 min
📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

All 100 Spring Framework questions · All topics