在配置bean实例时,xml中设置init和destroy方法:
<bean class="com.test.Demo" init-method="init" destroy-method="destroy"/>
public class Demo{ public void init() { System.out.println("Demo.class init method ..."); } public void destroy() { System.out.println("Demo.class destroy method ..."); } }
bean实现BeanPostProcessor接口,实现接口中的postProcessBeforeInitialization(初始化之前执行),postProcessAfterInitialization(bean初始化之后执行)
public class Demo implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("对象" + beanName + "开始初始化"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("对象" + beanName + "初试化完成"); return bean; } }
<bean id="demo" class="com.test.Demo" />
bean实现InitializingBean和DisposableBean接口
public class Demo implements InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("Demo.class init method ..."); } @Override public void destroy() throws Exception { System.out.println("Demo.class destroy method ..."); } }
<bean id="demo" class="com.test.Demo" />
使用@PostConstruct和@PreDestroy注解
@Component public class Demo { @PostConstruct public void init() { System.out.println("Demo .class init method ..."); } @PreDestroy public void destroy() { System.out.println("Demo .class destroymethod ..."); } }