本文共 2264 字,大约阅读时间需要 7 分钟。
有些对象实例化时,我们需要打开某些资源,而在销毁对象时将这些资源关闭,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