在spring应用程序开始时填充数据源



我想运行部分代码,以便在每次服务器启动时用虚拟数据填充数据库。我使用Tomcat作为servlet容器。我的应用程序使用Spring创建。是否有一个钩子,我可以在我的应用程序启动后运行我的代码来填充数据库?

你有两个不同的选择。

第一个是使用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,还有更简单的方法。

你可以使用Liquibase,如果你使用Spring Boot,你所要做的就是将liquibase-core添加到你的类路径,通过maven或任何你正在使用的构建工具。Spring Boot默认使用YAML文件。Spring Boot将在每次应用程序启动时运行Liquibase。

最新更新