欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

spring @PostConstruct 和 @PreDestroy注解使用示例,,使用@PostConst

来源: javaer 分享于  点击 48731 次 点评:165

spring @PostConstruct 和 @PreDestroy注解使用示例,,使用@PostConst


使用@PostConstruct 和 @PreDestroy分别处理bean的init-method和destroy-method。

下面实例说明如何使用这两个注解:

package cn.outofmemory.spring;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;public class CustomerService{    String message;    public String getMessage() {      return message;    }    public void setMessage(String message) {      this.message = message;    }    @PostConstruct    public void initIt() throws Exception {      System.out.println("Init method after properties are set : " + message);    }    @PreDestroy    public void cleanUp() throws Exception {      System.out.println("Spring Container is destroy! Customer clean up");    }}

在资源文件夹下添加spring.xml

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">    <bean id="customerService" class="cn.outofmemory.spring.CustomerService">        <property name="message" value="i'm property message" />    </bean></beans>

测试代码:

import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.outofmemory.spring.CustomerService;public class App {    public static void main( String[] args )    {        ConfigurableApplicationContext context =           new ClassPathXmlApplicationContext(new String[] {"spring.xml"});        CustomerService cust = (CustomerService)context.getBean("customerService");        System.out.println(cust);        context.close();    }}
相关栏目:

用户点评