发表时间:2011-05-17 最后修改:2011-05-17
猎头职位: 相关文章: 推荐群组: struts2 更多相关推荐 Bean 销毁前执行特定的操作,常用的设定方式有以下三种: 这是我们就有个疑问,这三种方式是完全等同的吗,孰先孰后? 首先,我们还是编写一个简单的测试代码: public class InitSequenceBean implements InitializingBean { public InitSequenceBean() { System.out.println("InitSequenceBean: constructor"); } @PostConstruct public void postConstruct() { System.out.println("InitSequenceBean: postConstruct"); } public void initMethod() { System.out.println("InitSequenceBean: init-method"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("InitSequenceBean: afterPropertiesSet"); } }
InitSequenceBean: constructor InitSequenceBean: postConstruct InitSequenceBean: afterPropertiesSet InitSequenceBean: init-method 通过上述输出结果,三者的先后顺序也就一目了然了: Constructor > @PostConstruct > InitializingBean > init-method Spring Spring public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass()); try { metadata.invokeInitMethods(bean, beanName); } catch (InvocationTargetException ex) { throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Couldn't invoke init method", ex); } return bean; }private LifecycleMetadata buildLifecycleMetadata(final Class clazz) { final LifecycleMetadata newMetadata = new LifecycleMetadata(); final boolean debug = logger.isDebugEnabled(); ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() { public void doWith(Method method) { if (initAnnotationType != null) { if (method.getAnnotation(initAnnotationType) != null) { newMetadata.addInitMethod(method); if (debug) { logger.debug("Found init method on class [" + clazz.getName() + "]: " + method); } } } if (destroyAnnotationType != null) { if (method.getAnnotation(destroyAnnotationType) != null) { newMetadata.addDestroyMethod(method); if (debug) { logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method); } } } } }); return newMetadata; } public CommonAnnotationBeanPostProcessor() { setOrder(Ordered.LOWEST_PRECEDENCE - 3); setInitAnnotationType(PostConstruct.class); setDestroyAnnotationType(PreDestroy.class); ignoreResourceType("javax.xml.ws.WebServiceContext"); }
Constructor > @PostConstruct > InitializingBean > init-method 本文源代码下载:https://lb-multi-demo.googlecode.com/svn/trunk/spring-lifecycle-test (责任编辑:JavaVideo) |
