欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Bean的初始化和销毁方法一:通过设置bean的initMethod和destroyMethod属性指定初始化和销毁方法。

程序员文章站 2022-05-21 23:06:04
...

1、pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.2</version>
    </dependency>
</dependencies>

2、实体类

public class Car {
    public Car () {
        System.out.println("car constructor...");
    }

    public void init () {
        System.out.println("car init...");
    }

    public void destory () {
        System.out.println("car destory");
    }
}

3、配置类

import com.it.huaxin.vo.Car;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LifeCycleConfig {
    @Bean(initMethod = "init", destroyMethod = "destory")
    public Car car() {
        return new Car();
    }
}

4、测试类

import com.it.huaxin.config.LifeCycleConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class LifeCycleTest {
    public static void main(String [] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
    }
}

//结果

car constructor...
car init...
car destory...

相关标签: 04 spring