可以使用JSR250规则定义的(java规范)两个注解来实现
@PostConstruct: 在Bean创建完成,且属于赋值完成后进行初始化,属于JDK规范的注解
@PreDestroy: 在bean将被移除之前进行通知, 在容器销毁之前进行清理工作
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、实体类
import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; public class Car { public Car () { System.out.println("car constructor..."); } @PostConstruct public void init() { System.out.println("car PostConstruct..."); } @PreDestroy public void destroy() { System.out.println("car PreDestroy..."); } }
3、配置类
import com.it.huaxin.vo.Car; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class LifeCycleConfig { @Bean 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); context.close(); } }
//结果:
car constructor...
car PostConstruct...
car PreDestroy...