In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
本篇文章给大家分享的是有关如何使用@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定制生命周期行为操作示例,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.