我有一个基于 Spring JDBC 和 Jersey RESTful Web 服务的 Web 应用程序。我正在使用以下 Spring JDBC 模板类来启动数据源并执行 SQL 脚本 (update_condition_table.sql):
public class CustomerJDBCTemplate implements CustomerDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
Resource rc = new ClassPathResource("update_condition_table.sql");
JdbcTestUtils.executeSqlScript(jdbcTemplateObject, rc, false);
}
// ......other methods
}
bean 配置文件是 beans.xml:
<!-- 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>
Jersey 控制器类包含类的实例化CustomerJDBCTemplate
并用作 REST Web 服务:
@Path("/customer")
public class CustomerService {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
CustomerJDBCTemplate dbController = (CustomerJDBCTemplate) context.getBean("customerJDBCTemplate");
// ... some GET/POST methods
}
当我通过在浏览器中输入索引 URL 启动我的 Web 应用程序时,该customerJDBCTemplate
bean 将执行 SQL 脚本。但是,当我点击导航到其他页面时,它崩溃并报告SQL脚本无法再次执行。所以很明显,在初始化数据源和初始启动索引网页之后,再次执行了 SQL 脚本。如何通过在 Web 应用程序初始启动时仅运行一次 SQL 脚本来避免这种情况?
看起来我需要将 bean 实例化代码移出CustomerService
类,但我应该把该代码放在哪里?