博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring 自定义对象初始化及销毁
阅读量:4050 次
发布时间:2019-05-25

本文共 2264 字,大约阅读时间需要 7 分钟。

– Start


有些对象实例化时,我们需要打开某些资源,而在销毁对象时将这些资源关闭,Spring 允许我们自定义初始化和销毁方法,下面是一个简单的例子。

package shangbo.spring.core.example9;public class OutPutService {	// 初始化方法	public void init() {		System.out.println("Enter init");	}	// 销毁方法	public void destroy() {		System.out.println("Enter destroy");	}	public void outPut() {		System.out.println("Hello World");	}}
package shangbo.spring.core.example9;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App {	public static void main(String[] args) {		// 实例化 Spring IoC 容器		ApplicationContext context = new ClassPathXmlApplicationContext("example.xml", OutPutService.class);		// 从容器中获得 OutPutService 对象		OutPutService printer = context.getBean(OutPutService.class);		// 使用对象		printer.outPut();	}}

如果你有很多这样的对象且它们的初始化和销毁方法名相同,我们可以定义默认的初始化和销毁方法。

如果使用 Java 配置文件,我们可以使用 @PostConstruct 和 @PreDestroy 注解,或@Bean(initMethod = “init”, destroyMethod = “destroy”)

package shangbo.spring.core.example11;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;public class OutPutService {	// 初始化方法	@PostConstruct	public void init() {		System.out.println("Enter init");	}	// 销毁方法	@PreDestroy	public void destroy() {		System.out.println("Enter destroy");	}	public void outPut() {		System.out.println("Hello World");	}}
package shangbo.spring.core.example11;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class AppConfig {	//@Bean(initMethod = "init", destroyMethod = "destroy")	@Bean	public OutPutService outPutService() {		return new OutPutService();	}}
package shangbo.spring.core.example11;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App {	public static void main(String[] args) {		// 实例化 Spring IoC 容器,也可以一次读取多个Java配置文件		ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);		// 从容器中获得 Service 对象		OutPutService printer = context.getBean(OutPutService.class);		// 使用对象		printer.outPut();	}}

– 声 明:转载请注明出处
– Last Updated on 2017-06-17
– Written by ShangBo on 2017-05-21
– End

你可能感兴趣的文章
Selenium-Switch与SelectApi接口详解
查看>>
Selenium-Css Selector使用方法
查看>>
Linux常用统计命令之wc
查看>>
测试必会之 Linux 三剑客之 sed
查看>>
Socket请求XML客户端程序
查看>>
Java中数字转大写货币(支持到千亿)
查看>>
Java.nio
查看>>
函数模版类模版和偏特化泛化的总结
查看>>
VMware Workstation Pro虚拟机不可用解决方法
查看>>
最简单的使用redis自带程序实现c程序远程访问redis服务
查看>>
redis学习总结-- 内部数据 字符串 链表 字典 跳跃表
查看>>
iOS 对象序列化与反序列化
查看>>
iOS 序列化与反序列化(runtime) 01
查看>>
iOS AFN 3.0版本前后区别 01
查看>>
iOS ASI和AFN有什么区别
查看>>
iOS QQ侧滑菜单(高仿)
查看>>
iOS 扫一扫功能开发
查看>>
iOS app之间的跳转以及传参数
查看>>
iOS __block和__weak的区别
查看>>
Android(三)数据存储之XML解析技术
查看>>