在非springboot的spring项目中要实现在项目启动后执行某个操作且在spring的bean生命周期内,可以通过实现InitializingBean
@Component public class InitDataListener implements InitializingBean { @Autowired TestMapper testMapper; @Autowired TestService testService; @Override public void afterPropertiesSet() throws Exception { System.out.println("==========="); List<Test> tests = testMapper.findAll(); System.out.println(tests); System.out.println("==========="); System.out.println(testService.findAllTests()); } }
启动后的结果:
16-Apr-2019 16:17:14.439 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.context.support.AbstractApplicationContext.prepareRefresh Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Apr 16 16:17:14 CST 2019]; root of context hierarchy 16-Apr-2019 16:17:14.497 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions Loading XML bean definitions from file [/Users/vincent/development/ide/learnProjects/webdemo/out/artifacts/webdemo_war_exploded/WEB-INF/classes/spring-servlet.xml] 16-Apr-2019 16:17:14.717 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions Loading XML bean definitions from file [/Users/vincent/development/ide/learnProjects/webdemo/out/artifacts/webdemo_war_exploded/WEB-INF/classes/spring-mybatis.xml] 16-Apr-2019 16:17:14.897 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties Loading properties file from class path resource [jdbc.properties] =========== 16-Apr-2019 16:17:21.757 信息 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/Users/vincent/development/tomcat/tomcat8/apache-tomcat-8.5.34/webapps/manager] 16-Apr-2019 16:17:21.802 信息 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/Users/vincent/development/tomcat/tomcat8/apache-tomcat-8.5.34/webapps/manager] has finished in [44] ms [Test{id=12, name='aaa'}, Test{id=13, name='bbb'}, Test{id=1, name='vincent'}, Test{id=2, name='json'}, Test{id=14, name='aaa'}, Test{id=15, name='bbb'}] =========== [Test{id=12, name='aaa'}, Test{id=13, name='bbb'}, Test{id=1, name='vincent'}, Test{id=2, name='json'}, Test{id=14, name='aaa'}, Test{id=15, name='bbb'}] 16-Apr-2019 16:17:41.524 信息 [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler Mapped URL path [/getUsets.do] onto handler 'indexController'