1 PackageCom.jt.mongo.demo.modules.init;2 3 ImportOrg.slf4j.Logger;4 Importorg.slf4j.LoggerFactory;5 ImportOrg.springframework.context.ApplicationListener;6 Importorg.springframework.context.event.ContextRefreshedEvent;7 ImportOrg.springframework.core.io.ClassPathResource;8 ImportOrg.springframework.jdbc.datasource.init.ResourceDatabasePopulator;9 Importorg.springframework.stereotype.Component;Ten One ImportJavax.annotation.Resource; A ImportJavax.sql.DataSource; - Importjava.sql.SQLException; - the @Component - Public classSqlscriptinitexecutorImplementsApplicationlistener<contextrefreshedevent> { - - Private Static FinalLogger Logger = Loggerfactory.getlogger (sqlscriptinitexecutor.class); + - @Resource + PrivateDataSource Mysqldatasource; A at @Override - Public voidonapplicationevent (Contextrefreshedevent event) { - initmysqltables (); - } - - Private voidInitmysqltables () { in Try { - toResourcedatabasepopulator Populator =Newresourcedatabasepopulator (); +Populator.addscript (NewClasspathresource ("Sql/mysql_pdca_manager.sql")); - populator.populate (Mysqldatasource.getconnection ()); the *Logger.info ("Init PDCA Manager tables success."); $ Panax Notoginseng}Catch(SQLException e) { -Logger.error ("Init PDCA Manager Tables Error", e); the } + } A}
Contextrefreshedevent:
Event raised when an {@code ApplicationContext} gets initialized or refreshed.
When the container is initialized or restarted, it is instantiated into the container, and then listening to his listener executes
Execute and execute database scripts after container startup