项目在加载完毕后马上执行afterPropertiesSet 方法 ,而且可使用spring 注入好的beanspring
第一种方式
写一个类,实现BeanPostProcessor,这个接口有两个方法
(1)postProcessBeforeInitialization方法,在spring中定义的bean初始化前调用这个方法;
(2)postProcessAfterInitialization方法,在spring中定义的bean初始化后调用这个方法;
这个虽然也能执行,可是是每次加载一个bean都会去执行,不太知足个人要求,我只须要一次就ok了,可是这个接口针对某个专门的bean有用ide
第二种方式 编写一个实现ApplicationListener的listener类post
@Service public class StartupListener implements ApplicationListener<ContextRefreshedEvent > { public static String ShopNum ; @Autowired ShopService shopService; @Override public void onApplicationEvent(ContextRefreshedEvent event) { if ( event.getApplicationContext (). getParent() == null) { // TODO 这里写下将要初始化的内容 Shop shopByShopNum = shopService .getShopByShopNum ("e7-80-2e-e8-6c-a6" ); System.out .println ("----------------------------" ); } }}
最后一种方式编写InitializingBean的实现类code
@Service public class Test implements InitializingBean{ @Autowired ShopService shopService; @Override public void afterPropertiesSet() throws Exception { Shop shopByShopNum = shopService.getShopByShopNum( "e7-80-2e-e8-6c-a6"); System.out .println ("----------------------------" ); } }
项目在加载完毕后马上执行afterPropertiesSet 方法 ,而且可使用spring 注入好的bean接口