java static 变量 初始化一次_关于java static变量初始化的疑问
java中,類的static變量作為類變量,只需要被一次初始化,就可使用,但是,我在程序中遇到一個問題:
在web.xml中配置listener,服務器啟動時,ServletContextListen初始化數據源(DataSource),第一次初始化成功,但是在Test類中,調用ConnectionManager.getConnection()時,DataSource卻為null,意味著ServletContextListen初始化數據源失敗了,大家幫忙解答下,到底什么原因造成的,謝謝!!!
以下是代碼:
package c3p0.connection;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class ConnectionManager {
private static DataSource data_source=null;;
private static Properties props=null;
private static String porps_name=null;
/**
* 創建數據庫連接池
* @return
*/
private static DataSource createDataSource(){
load();
data_source=initDB();
return data_source;
}
/**
* 加載配置文件
*/
private static void load(){
try {
props = new Properties();
InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream(porps_name);
props.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 初始化數據庫
*/
private static DataSource initDB(){
System.out.println("開始初始化數據源...");
ComboPooledDataSource pool_ds=new ComboPooledDataSource();
try {
pool_ds.setDriverClass(getProperty("c3p0.connection.driverClass"));
} catch (PropertyVetoException e) {
e.printStackTrace();
throw new RuntimeException("數據庫驅動加載失敗");
}
pool_ds.setJdbcUrl(getProperty("c3p0.connection.url"));
pool_ds.setUser(getProperty("c3p0.connection.user"));
pool_ds.setPassword(getProperty("c3p0.connection.password"));
pool_ds.setInitialPoolSize(Integer.parseInt(getProperty("c3p0.connection.initialPoolSize")));
pool_ds.setMaxPoolSize(Integer.parseInt(getProperty("c3p0.connection.maxPoolSize")));
pool_ds.setMinPoolSize(Integer.parseInt(getProperty("c3p0.connection.minPoolSize")));
pool_ds.setMaxIdleTime(Integer.parseInt(getProperty("c3p0.connection.maxIdleTime")));
pool_ds.setAcquireIncrement(Integer.parseInt(getProperty("c3p0.connection.acquireIncrement")));
pool_ds.setAcquireRetryAttempts(Integer.parseInt(getProperty("c3p0.connection.acquireRetryAttempts")));
pool_ds.setAcquireRetryDelay(Integer.parseInt(getProperty("c3p0.connection.acquireRetryDelay")));
pool_ds.setTestConnectionOnCheckout(Boolean.parseBoolean(getProperty("c3p0.connection.testConnectionOnCheckout")));
pool_ds.setTestConnectionOnCheckin(Boolean.parseBoolean(getProperty("c3p0.connection.testConnectionOnCheckin")));
pool_ds.setIdleConnectionTestPeriod(Integer.parseInt(getProperty("c3p0.connection.idleConnectionTestPeriod")));
pool_ds.setCheckoutTimeout(Integer.parseInt(getProperty("c3p0.connection.checkoutTimeout")));
pool_ds.setAutomaticTestTable(getProperty("c3p0.connection.automaticTestTable"));
System.out.println("數據源初始化完畢...");
return pool_ds;
}
/**
* 獲取c3p0連接池文件配置信息
* @param key
* @return
*/
private static String getProperty(String key){
if(key==null||"".equals(key)){
throw new NullPointerException("key不能為空!!!請檢查key的賦值!!!");
}
return props.getProperty(key);
}
public static Connection getConnection() throws SQLException{
data_source=(data_source==null) ? createDataSource() : data_source;
return data_source.getConnection();
}
public static void start(String porps_name) throws SQLException{
ConnectionManager.porps_name=porps_name;
Connection conn=getConnection();
conn.close();
}
public static void stop(){
data_source=null;
}
public static void release(Connection conn,PreparedStatement pstmt,ResultSet res){
try {
if(conn!=null){
conn.close();
}
if(pstmt!=null){
pstmt.close();
}
if(res!=null){
res.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package mystruts.listener;
import java.sql.SQLException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import c3p0.connection.ConnectionManager;
/**
* ServletContext 上下文監聽器
* 應用服務器一啟動就產生該對象,服務器關閉即銷毀
* 作用于全局,所有Servlet ,相當于靜態變量
* @author tianly
*
*/
public class ServletContextListen implements ServletContextListener {
/**
* web服務器關閉時執行
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
/**
* 關閉數據源
*/
ConnectionManager.stop();
}
/**
* web服務器啟動時執行
*/
@Override
public void contextInitialized(ServletContextEvent event) {
/**
* 初始化數據源
*/
String db_url=event.getServletContext().getInitParameter("DataBaseConfig");
try {
ConnectionManager.start(db_url);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package test.c3p0;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import c3p0.connection.ConnectionManager;
import c3p0.util.DateUtil;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
String currdate=DateUtil.getDateTime();
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet res=null;
try {
String sql="insert into userinfo(username,password,sex,regdate) values(?,?,?,?)";
String sql4ID="select LAST_INSERT_ID()";
conn=ConnectionManager.getConnection();
conn.setAutoCommit(false);
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, "tly");
pstmt.setString(2, "tly");
pstmt.setInt(3, 0);
pstmt.setString(4, currdate);//mysql中無需進行日期格式轉換
pstmt.executeUpdate();
pstmt=conn.prepareStatement(sql4ID);
res=pstmt.executeQuery();
if(res.next()){
int ID=res.getInt(1);
System.out.println("ID:"+ID);
}
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
ConnectionManager.release(conn, pstmt, res);
}
}
}
mysystem
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
ActionDispatcher
mystruts.actionfilter.ActionDispatcher
ActionDispatcher
*.action
DataBaseConfig
c3p0/c3p0.properties
mystruts.listener.ServletContextListen
在Test類中,調用ConnectionManager.getConnection()時,DataSource卻為null,但我在debug時,跟蹤查看,發現DataSource是被初始化了,不知什么原因造成初始化失敗,請大家幫忙查看下,謝謝
總結
以上是生活随笔為你收集整理的java static 变量 初始化一次_关于java static变量初始化的疑问的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 304_分析HTTP请求返回3
- 下一篇: 蓝桥杯第七 java决赛_第七届(16年