Spring InitializingBean和init-method
原文转自:http://blog.csdn.net/shaozheng1006/article/details/6916940
InitializingBean
在spring 初始化后,执行完所有属性设置方法(即setXxx)将自动调用 afterPropertiesSet(), 在配置文件中无须特别的配置, 但此方式增加了bean对spring 的依赖,应该尽量避免使用
public interface InitializingBean
{
public abstract void afterPropertiesSet()
throws Exception;
}
package research.spring.beanfactory.ch4;import org.springframework.beans.factory.InitializingBean;public class LifeCycleBean implements InitializingBean{public void afterPropertiesSet() throws Exception {System.out.println("LifeCycleBean initializing...");}}
xml version="1.0" encoding="UTF-8"?>DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN""http://www.springframework.org/dtd/spring-beans.dtd"><beans><bean name="lifeBean" class="research.spring.beanfactory.ch4.LifeCycleBean">bean>beans>
package research.spring.beanfactory.ch4;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;public class LifeCycleTest {public static void main(String[] args) {XmlBeanFactory factory=new XmlBeanFactory(new ClassPathResource(
"research/spring/beanfactory/ch4/context.xml"));factory.getBean("lifeBean");}}
SHAPE \* MERGEFORMAT
装配bean的合作者 |
查看bean是否实现InitializingBean接口 |
调用afterPropertiesSet方法 |
init-method
package research.spring.beanfactory.ch4;public class LifeCycleBean{public void init(){System.out.println("LifeCycleBean.init...");}}
xml version="1.0" encoding="UTF-8"?>DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN""http://www.springframework.org/dtd/spring-beans.dtd"><beans><bean name="lifeBean" class="research.spring.beanfactory.ch4.LifeCycleBean"
init-method="init">bean>beans>
final protected void init() throws Exception{
System.out.println("init method...");
if(true) throw new Exception("init exception");
如果一个bean被定义为非单例的,那么afterPropertiesSet和init-method在bean的每一个实例被创建时都会执行。单例 bean的afterPropertiesSet和init-method只在bean第一次被实例时调用一次。大多数情况下 afterPropertiesSet和init-method都应用在单例的bean上。
<二>
init-method
在bean中写一个无参无返回值的public 方法 实现bean的初始化。例如
public void init(){
// …… 初始化代码
}
在spring 初始化后,执行完所有属性设置方法(即setXxx)将自动调用 配置文件init-method指定的方法,配置文件如下所示
<bean name="beanName" class="package.bean"
init-method="init">
</bean>
<三>
下面是一个小例子,initializingBean接口和init-method都实现了,可以自己随便改。
试验用的bean:
package researchspring.beanfactory;
import org.springframework.beans.factory.InitializingBean;
public class LifeCycleBean implements InitializingBean{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void afterPropertiesSet() throws Exception {
System.out.println("Implements initializing start.....");
if(name == null)
System.out.println("configuration failed!");
System.out.println("Implements initializing end!");
}
public void init() {
System.out.println("init() initializing start.....");
if(name == null)
System.out.println("configuration failed!");
System.out.println("init() initializing end!");
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.0.xsd">
<bean id="lifeBean" class="researchspring.beanfactory.LifeCycleBean"
init-method="init" >
<property name="name" value="apple"></property>
</bean>
</beans>
测试类:
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
LifeCycleBean lifeBean = (LifeCycleBean)ac.getBean("lifeBean");
}
}
×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××
另外,从网上找了这么一段
//……
//在一个bean的合作者设备完成后,执行一个bean的初始化方法。 protected void invokeInitMethods(String beanName, Object bean, RootBeanDefinition mergedBeanDefinition)
throws Throwable {
//判断bean是否实现了InitializingBean接口 if (bean instanceof InitializingBean) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
//调用afterPropertiesSet方法 ((InitializingBean) bean).afterPropertiesSet();
}
//判断bean是否定义了init-method if(mergedBeanDefinition!=null&&mergedBeanDefinition.getInitMethodName() != null) {
//调用invokeCustomInitMethod方法来执行init-method定义的方法 invokeCustomInitMethod(beanName, bean, mergedBeanDefinition.getInitMethodName());
}
}
//执行一个bean定义的init-method方法 protected void invokeCustomInitMethod(String beanName, Object bean, String initMethodName)
throws Throwable {
if (logger.isDebugEnabled()) {
logger.debug("Invoking custom init method '" + initMethodName +
"' on bean with name '" + beanName + "'");
}
//使用方法名,反射Method对象 Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null);
if (initMethod == null) {
throw new NoSuchMethodException(
"Couldn't find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'");
}
//判断方法是否是public if (!Modifier.isPublic(initMethod.getModifiers())) {
//设置accessible为true,可以访问private方法。
initMethod.setAccessible(true);
}
try {
//反射执行这个方法 initMethod.invoke(bean, (Object[]) null);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
//………..
Spring InitializingBean和init-method的更多相关文章
- spring init method destroy method
在java的实际开发过程中,我们可能常常需要使用到init method和destroy method,比如初始化一个对象(bean)后立即初始化(加载)一些数据,在销毁一个对象之前进行垃圾回收等等. ...
- Spring报错: org.springframework.beans.factory.support.BeanDefinitionValidationException: Couldn't find an init method named 'init' on bean with name 'car'(待解答)
在Spring工程里,有一个Car类的bean,Main.java主程序,MyBeanPostProcessor.java是Bean后置处理器. 文件目录结构如下: Car.java package ...
- MyBatis与Spring MVC结合时,使用DAO注入出现:Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
错误源自使用了这个例子:http://www.yihaomen.com/article/java/336.htm,如果运行时会出现如下错误: Invocation of init method fai ...
- Error creating bean with name 'sqlSessionFactory' defined in class path resource [config/spring/applicationContext.xml]: Invocation of init method failed;
我报的错: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSes ...
- Spring InitializingBean and DisposableBean example
In Spring, InitializingBean and DisposableBean are two marker interfaces, a useful way for Spring to ...
- Spring InitializingBean init-method @PostConstruct 执行顺序
Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,常用的设定方式有以下三种: 通过实现 Initializing ...
- java代码中init method和destroy method的三种使用方式
在java的实际开发过程中,我们可能常常需要使用到init method和destroy method,比如初始化一个对象(bean)后立即初始化(加载)一些数据,在销毁一个对象之前进行垃圾回收等等. ...
- MyBatis笔记----报错:Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/ij34/mybatis/applicationContext.xml]: Invocation of init method failed; nested exception is org.sp
四月 05, 2017 4:51:02 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRef ...
- Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable t
spring与hibernate整合然后出现如下错误: org.springframework.beans.factory.BeanCreationException: Error creating ...
随机推荐
- swift 附属脚本
附属脚本是访问对象,集合或序列的快捷方式 struct STest{ let constValue:Int subscript(count:Int)->Int{ return count*con ...
- Word2010撤销按钮失效,Ctrl+Z失效解决办法
1.打开注册表编辑器.按Win+R,在运行框中键入regedit,然后单击“确定”. 2.在注册表编辑器中,展开到下列注册表子项: HKEY_CURRENT_USER\Software\Microso ...
- ubuntu下查看环境变量
在Windows下,查看环境变量的命令是:set,这个命令会输出系统当前的环境变量. Linux下准确的说是REDHAT下应该如何查看呢,命令是: export 如果你想查看某一个名称的环 ...
- 使用hessian+protocol buffer+easyUI综合案例--登陆
首先先简单介绍下hessian ,protocol buffer, easyUI框架 hessian: Hessian是一个轻量级的remoting on http工具,采用的是Binary RPC协 ...
- 个人对joomla3.2x和joomla2.5X浅薄看法
很久没有写joomla文章了,发现想写的东西还是挺多的,后面抽时间补回来,其实更多还是php的一些东西.joomla3.0以后系统改变挺大,后台都是用bootstrap作为主题,个人对这个无爱,因为他 ...
- vmware workstation11+centos7+lnmp一键安装包 环境搭建
vmware workstation11 1.下载:http://pan.baidu.com/s/1gecipOJ 2.安装:直接下一步. centos7 1.下载:网易镜像 http://mirro ...
- ruby -- 进阶学习(十七)应用代码优化
ROR开发,代码优化的方法下面这两项是比较重要的: link_to Rails的link_to是非常慢的,它的代码实现过于复杂,特别是Rails1.2引入了REST以后,大量的命名路由被使用,这些命 ...
- ruby -- 问题解决(八)解决Paperclip::NotIdentifiedByImageMagickError
好吧!又见 Paperclip::NotIdentifiedByImageMagickError,之前遇过一次... 最近又遇到一次,解决了之后,忘了写博客,然后再次遇到的时候,有一种被车撞到的节奏. ...
- Linux命令:ps / top
简介:ps - report a snapshot of the current processes. 用途:获取当前时刻程序运行状态 概要:ps [options] 类型:ps is hashed ...
- PEP8 Python 编码规范
一 代码编排1 缩进.4个空格的缩进(编辑器都可以完成此功能),不使用Tap,更不能混合使用Tap和空格.2 每行最大长度79,换行可以使用反斜杠,最好使用圆括号.换行点要在操作符的后边敲回车.3 类 ...