如何在Spring启动时只执行一次SQL脚本?
我有一个基于SpringJDBC和Jersey RESTfulWeb服务的web应用程序。我使用以下SpringJDBC模板类来启动数据源并执行SQL脚本(update_condition_table.SQL): bean配置文件是beans.xml:如何在Spring启动时只执行一次SQL脚本?,spring,jersey,spring-jdbc,Spring,Jersey,Spring Jdbc,我有一个基于SpringJDBC和Jersey RESTfulWeb服务的web应用程序。我使用以下SpringJDBC模板类来启动数据源并执行SQL脚本(update_condition_table.SQL): bean配置文件是beans.xml: <!-- Initialization for data source --> <bean id="dataSource" class="org.springframework.jdbc.datasource.Drive
<!-- Initialization for data source -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/customer" />
<property name="username" value="root" />
<property name="password" value="mypassword" />
</bean>
<!-- Definition for customerJDBCTemplate bean -->
<bean id="customerJDBCTemplate" class="com.example.db.CustomerJDBCTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
当我通过在浏览器中输入索引URL启动web应用程序时,SQL脚本由customerJDBCTemplate
bean执行。但是,当我单击导航到其他页面时,它崩溃并报告SQL脚本无法再次执行。显然,SQL脚本是在初始化数据源和初始启动索引网页之后再次执行的。如何通过在web应用程序初始启动时只运行一次SQL脚本来避免这种情况
看起来我需要将bean实例化代码移出
CustomerService
类,但是我应该将代码放在哪里?让CustomerJDBCTemplate实现AfterPropertieSet
将在Spring的BeanFactory设置完所有属性之后被调用一次
例如:
public class CustomerJDBCTemplate implements CustomerDAO, InitializingBean {
...
// ......other methods
public void afterPropertiesSet() throws Exception {
//do your initializing, or call your initializing methods
}
}
我发现我应该在
CustomerService
类中将bean应用程序上下文设置为静态,并在静态初始化块中执行,如下所示:
@Path("/customer")
public class CustomerService {
private static ApplicationContext context;
private static CustomerJDBCTemplate dbController;
static {
context = new ClassPathXmlApplicationContext("beans.xml");
dbController = (CustomerJDBCTemplate) context.getBean("customerJDBCTemplate");
}
//... other methods
}
我想原因是Jersey为每个HTTP会话创建了一个不同的
CustomerService
实例(如果我错了,请纠正我)。因此,如果我将bean上下文设置为实例变量,它将为每个HTTP请求进行初始化 我试过之后,这没用。然而,我找到了正确的方法(见下面我的自我回答)。
public class CustomerJDBCTemplate implements CustomerDAO, InitializingBean {
...
// ......other methods
public void afterPropertiesSet() throws Exception {
//do your initializing, or call your initializing methods
}
}
@Path("/customer")
public class CustomerService {
private static ApplicationContext context;
private static CustomerJDBCTemplate dbController;
static {
context = new ClassPathXmlApplicationContext("beans.xml");
dbController = (CustomerJDBCTemplate) context.getBean("customerJDBCTemplate");
}
//... other methods
}