Get the App
SLTechnology News&Howtos  ›  Development  › 

How to customize lifecycle behavior action examples using @ POSTConstruct and @ PreDestroy

Shulou Source: shulou.com Published: 2022-06-03 06:02:59 10月04日 Update

本篇文章给大家分享的是有关如何使用@POSTConstruct和@PreDestroy定制生命周期行为操作示例,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

一 配置

二 接口

Axe

package org.crazyit.app.service;public interface Axe{ public String chop();}Personpackage org.crazyit.app.service;public interface Person{ public void useAxe();}

三 Bean

Chinese

package org.crazyit.app.service.impl;import org.springframework.stereotype.*;import javax.annotation.*;import org.crazyit.app.service.*;@Componentpublic class Chinese implements Person{ // 执行Field注入 @Resource(name="steelAxe") private Axe axe; // 实现Person接口的useAxe()方法 public void useAxe() { // 调用axe的chop()方法, // 表明Person对象依赖于axe对象 System.out.println(axe.chop()); } @PostConstruct public void init() { System.out.println("正在执行初始化的init方法..."); } @PreDestroy public void close() { System.out.println("正在执行销毁之前的close方法..."); }}

SteelAxe

package org.crazyit.app.service.impl;import org.springframework.stereotype.*;import org.crazyit.app.service.*;@Componentpublic class SteelAxe implements Axe{ public String chop() { return "钢斧砍柴真快"; }}

StoneAxe

package org.crazyit.app.service.impl;import org.springframework.stereotype.*;import org.crazyit.app.service.*;@Componentpublic class StoneAxe implements Axe{ public String chop() { return "石斧砍柴好慢"; }}

四 测试类

package lee;import org.springframework.context.*;import org.springframework.context.support.*;import org.crazyit.app.service.*;public class BeanTest{ public static void main(String[] args) { // 创建Spring容器 AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 注册关闭钩子 ctx.registerShutdownHook(); Person person = ctx.getBean("chinese" , Person.class); person.useAxe(); }}

五 测试结果

正在执行初始化的init方法...钢斧砍柴真快正在执行销毁之前的close方法...

以上就是如何使用@POSTConstruct和@PreDestroy定制生命周期行为操作示例,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。

Tags: Method cycle life example behavior object interface more knowledge article steel axe test utility container that is work meeting article look knowledge point Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei MariaDB NVidia Xiaomi MySQL