博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
简单比较init-method,afterPropertiesSet和BeanPostProcessor
阅读量:7155 次
发布时间:2019-06-29

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

一、简单介绍

1、init-method方法,初始化bean的时候执行,可以针对某个具体的bean进行配置。init-method需要在applicationContext.xml配置文档中bean的定义里头写明。例如:

这样,当TestBean在初始化的时候会执行TestBean中定义的init方法。

2、afterPropertiesSet方法,初始化bean的时候执行,可以针对某个具体的bean进行配置。afterPropertiesSet 必须实现 InitializingBean接口。实现 InitializingBean接口必须实现afterPropertiesSet方法。

3、BeanPostProcessor,针对所有Spring上下文中所有的bean,可以在配置文档applicationContext.xml中配置一个BeanPostProcessor,然后对所有的bean进行一个初始化之前和之后的代理。BeanPostProcessor接口中有两个方法: postProcessBeforeInitialization和postProcessAfterInitialization。 postProcessBeforeInitialization方法在bean初始化之前执行, postProcessAfterInitialization方法在bean初始化之后执行。

总之,afterPropertiesSet 和init-method之间的执行顺序是afterPropertiesSet 先执行,init-method 后执行。从BeanPostProcessor的作用,可以看出最先执行的是postProcessBeforeInitialization,然后是afterPropertiesSet,然后是init-method,然后是postProcessAfterInitialization。

二、相关用法及代码测试

该PostProcessor类要作为bean定义到applicationContext.xml中,如下

2、TestBean类,用做测试Bean,观察该Bean初始化过程中上面4个方法执行的先后顺序和内容。实现InitializingBean接口,并且实现接口中的afterPropertiesSet方法。最后定义作为init-method的init方法。

结果如下:

------------------------------

对象TestBean开始实例化

******************************

afterPropertiesSet is called

******************************

init-method is called

******************************

对象TestBean实例化完成

------------------------------

3、比较BeanFactoryPostProcessor和BeanPostProcessor

BeanFactoryPostProcessor在bean实例化之前执行,之后实例化bean(调用构造函数,并调用set方法注入属性值),然后在调用两个初始化方法前后,执行了BeanPostProcessor。初始化方法的执行顺序是,先执行afterPropertiesSet,再执行init-method。

转载地址:http://dfrgl.baihongyu.com/

你可能感兴趣的文章
css与css3对比
查看>>
day7-select Port multiplexing, multiple IO
查看>>
查看哪些用户登录了ftp服务器
查看>>
学习Nagios(1)监控门禁
查看>>
30个优秀的大自然风格网页设计作品欣赏
查看>>
Touch事件传递顺序。
查看>>
用ipset配置linux防火墙
查看>>
phpmyadmin中提示“缺少mysqli扩展,请检查PHP设置”
查看>>
js 点击事件处理
查看>>
我的友情链接
查看>>
TeamViewerPortable远程桌面连接软件使用
查看>>
jfinal抽象Service方法
查看>>
《java编程思想》学习笔记——持有对象
查看>>
Centos下的Redis安装简介
查看>>
telnet 命令使用方法详解
查看>>
重装win7系统后修复linux启动引导
查看>>
flask文件上传及访问显示的实现
查看>>
我的友情链接
查看>>
VS 添加头部注释的具体内容
查看>>
erlang 利用 ssh 远程执行 shell 命令
查看>>