我希望运行某些代码,以便每次服务器启动时使用虚拟数据填充数据库。我使用Tomcat作为我的servlet容器。我的应用程序是使用Spring创建的。是否有一个钩子,我可以在我的应用程序启动后运行我的代码来填充数据库?
答案 0 :(得分:2)
您有两种不同的选择。
第一个是使用Spring的DataSourceInitializer
。您可以将初始化查询作为参数传递,然后执行该查询。您可以执行任何您喜欢的命令。
示例:
<bean id="dbInitializer" class="org.springframework.jdbc.datasource.init.DataSourceInitializer">
<property name="dataSource" ref="myDataSourceRef"/>
<property name="enabled" value="true"/>
<property name="databasePopulator">
<bean class="org.springframework.jdbc.datasource.init.ResourceDatabasePopulator">
<property name="continueOnError" value="true"/>
<property name="ignoreFailedDrops" value="true"/>
<property name="sqlScriptEncoding" value="UTF-8"/>
<property name="scripts">
<array>
<value type="org.springframework.core.io.Resource">init.sql</value>
</array>
</property>
</bean>
</property>
</bean>
第二种方法是实现Spring ApplicationListener
。手动将每个数据从该侦听器填充到数据库。实现起来有点困难。
示例:
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class ApplicationListenerBean implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
// now you can do applicationContext.getBean(...)
// ...
}
}
}
这个bean必须由Spring初始化。您可以在applicationContext.xml
或配置类中定义它。
顺便说一句,您始终可以使用ServletContextListener
来监听ServletContext状态。但是如果你使用Spring,那么有更简单的方法。
答案 1 :(得分:1)
您可以使用Liquibase,如果您正在使用Spring Boot,则只需将liquibase-core
添加到您的类路径,通过maven或您正在使用的任何构建工具是。 Spring Boot默认使用YAML文件。然后,Spring Boot将在每次应用程序启动时运行Liquibase。