一、接口
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方法。