Jerry's Blog

Recording what I learned everyday

View on GitHub


28 April 2019

Spring(6)----Lifecycle Callbacks

by Jerry Zhang

#Tip of the Day:

1. Tomcat server, be careful with the Application context!

2. If we use Spring boot to start a server, we must add a dependency: spring-boot-starter-web



Video Link

Lifecycle Callbacks

Sometimes, we want to execute some logic when a bean is initialized. In this case, we can use an initialization callback.

There are many ways to define the init function, for example

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {

    public void init() {
        // do some initialization work
    }
}

However, on Spring’s official website, @PostConstruct and @PreDestroy are suggested.

In the Bean class, define two methods with these two annotation:

@Component
public class TestBean {

    @PostConstruct
    public void onInit(){
        System.out.println("TestBean.onInit");
    }

    @PreDestroy
    public void onDestroy(){
        System.out.println("TestBean.onDestroy");
    }
}

Then test our bean:

public class Class017Test {

    @Test
    public void test(){
        AbstractApplicationContext context =
                new AnnotationConfigApplicationContext(TestConfiguration.class);

        TestBean testBean = context.getBean("testBean", TestBean.class);
        System.out.println("testBean = " + testBean);
        context.close();
    }
}

The result is:

TestBean.onInit
testBean = springioc.class017.TestBean@3bd40a57
TestBean.onDestroy
tags: Java, - Spring, - Spring - framework, - Bean, - Lifecycle - Callbacks