一、接口
public interface InitializingBean { /** * Invoked by a BeanFactory after it has set all bean properties supplied * (and satisfied BeanFactoryAware and ApplicationContextAware). * <p>This method allows the bean instance to perform initialization only * possible when all bean properties have been set and to throw an * exception in the event of misconfiguration. * @throws Exception in the event of misconfiguration (such * as failure to set an essential property) or if initialization fails. */ void afterPropertiesSet() throws Exception; }
二、作用
利用spring的InitializingBean的afterPropertiesSet來初始化,直接看下面的demo
①、接口定義
public interface InitializingService { public void say(); }
②、接口實現類
@Component("initializingService") public class InitializingServiceImpl implements InitializingService, InitializingBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("call InitializingBean"); } @Override public void say() { System.out.println("call say"); } }
③、獲取bean上下文工具類實現
public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; // Spring應用上下文環境 @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } /** * 獲取對象 * * @param name * @return Object 一個以所給名字注冊的bean的實例 * @throws BeansException */ public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } }
xml配置 : spring xml 文件注入
<bean id="springContextUtil" class="com.mycompany.yuanmeng.springdemo.aop.SpringContextUtil" />
④、測試
public class InitializingBeanDemo { public static void main(String[] args) { new ClassPathXmlApplicationContext("spring.xml"); // 加載ApplicationContext(模擬啟動web服務) InitializingService service = (InitializingService) SpringContextUtil.getBean("initializingService"); service.say(); } }
⑤、結果
call InitializingBean
call say
這說明在spring初始化bean的時候,如果bean實現了InitializingBean接口,會自動調用afterPropertiesSet方法。