InitializingBean接口為bean提供了初始化方法的方式惦辛,它只包括afterPropertiesSet方法,凡是繼承該接口的類(lèi)条舔,在初始化bean的時(shí)候會(huì)執(zhí)行該方法叙赚。
測(cè)試程序如下:
/**
* @author jy
* @date 2018年5月15日
* <p>Description: </p>
*/
package com.dubbo.service.impl;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
/**
*
*
*/
@Component("testBean")
public class TestInitializeBean implements InitializingBean{
/* (non-Javadoc)
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("initialize bean");
}
}
main程序如下
/**
* @author
* @date 2018年5月4日
* <p>Description: </p>
*/
package dubboprovider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dubbo.service.impl.UserServiceImpl;
/**
* @author
*
*/
public class ApplicationTest {
/**
* @param args
*<p>Description: </p>
*/
public static void main(String[] args) {
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
context.start();
// UserServiceImpl userServiceImpl=(UserServiceImpl) context.getBean("userService");
// String n=userServiceImpl.getName("10");
synchronized (ApplicationTest.class) {
while(true){
try {
ApplicationTest.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
運(yùn)行main程序結(jié)果
這說(shuō)明在spring初始化bean的時(shí)候,如果bean實(shí)現(xiàn)了InitializingBean接口拭荤,會(huì)自動(dòng)調(diào)用afterPropertiesSet方法茵臭。
實(shí)現(xiàn)InitializingBean接口與在配置文件中指定init-method有什么不同?
修改配置文件舅世,加上init-method配置旦委,修改如下:
<bean id="testBean"
class="com.dubbo.service.impl.TestInitializeBean" init-method="testInitial">
</bean>
運(yùn)行main程序,結(jié)果
由結(jié)果可看出雏亚,在spring初始化bean的時(shí)候缨硝,如果該bean是實(shí)現(xiàn)了InitializingBean接口,并且同時(shí)在配置文件中指定了init-method罢低,系統(tǒng)則是先調(diào)用afterPropertiesSet方法查辩,然后在調(diào)用init-method中指定的方法。
總結(jié)
1:spring為bean提供了兩種初始化bean的方式奕短,實(shí)現(xiàn)InitializingBean接口宜肉,實(shí)現(xiàn)afterPropertiesSet方法,或者在配置文件中同過(guò)init-method指定翎碑,兩種方式可以同時(shí)使用
2:實(shí)現(xiàn)InitializingBean接口是直接調(diào)用afterPropertiesSet方法谬返,比通過(guò)反射調(diào)用init-method指定的方法效率相對(duì)來(lái)說(shuō)要高點(diǎn)。但是init-method方式消除了對(duì)spring的依賴(lài)
3:如果調(diào)用afterPropertiesSet方法時(shí)出錯(cuò)日杈,則不調(diào)用init-method指定的方法遣铝。總結(jié)
1:spring為bean提供了兩種初始化bean的方式莉擒,實(shí)現(xiàn)InitializingBean接口酿炸,實(shí)現(xiàn)afterPropertiesSet方法,或者在配置文件中同過(guò)init-method指定涨冀,兩種方式可以同時(shí)使用
2:實(shí)現(xiàn)InitializingBean接口是直接調(diào)用afterPropertiesSet方法填硕,比通過(guò)反射調(diào)用init-method指定的方法效率相對(duì)來(lái)說(shuō)要高點(diǎn)。但是init-method方式消除了對(duì)spring的依賴(lài)
3:如果調(diào)用afterPropertiesSet方法時(shí)出錯(cuò),則不調(diào)用init-method指定的方法扁眯。
Map<K, V> CACHES = new ConcurrentHashMap<K, V>();還有這個(gè)