2019-06-20

//餓漢式:

? ? ? ? public class Singleton{

private static Singleton singleton =new Singleton ();

private Singleton (){}

public static Singleton getInstance(){return singletion;}

}

//懶漢式:

? ? ? public class Singleton{

private static Singleton singleton =null;

public static synchronized Singleton getInstance(){

if(singleton==null){

singleton =new Singleton();

}

return singleton;

}

}

將文件變成字節(jié)流

InputStream inputStream = ConfigManager.class.getClassLoader().getResourceAsStream(file);

1.單例模式定義

? ??????單例模式是一種常用的軟件設(shè)計(jì)模式,其定義是單例對(duì)象的類只能允許一個(gè)實(shí)例存在。

? ? ? ? 1)properties讀取配置文件

? ? ? ? ? ? 配置文件內(nèi)容:

? ??????????????driverClassName=com.mysql.jdbc.Driver

????????????????url=jdbc:mysql:///day14

????????????????username=root

????????????????password=wang

? ? 讀取配置文件的過程

? ? ? ? ? ? Properties pro = new Properties();

? ? ? ? ? ?pro.load( ConfigManager.class.getClassLoader().getResourceAsStream(file));

3.DataSource數(shù)據(jù)源配置文件? ? ? ??

? ? ? ?路徑: tomcat-config-context.xml? ?

? ??????<Resource name="jdbc/news"

????????????auth="Container"? type="javax.sql.DataSource"? maxActive="100"

????????????maxIdle="30" maxWait="10000" username="root"? password="wang"

????????????driverClassName="com.mysql.jdbc.Driver"

????????????url="jdbc:mysql://127.0.0.1:3306/news?characterEncoding=UTF-8"/>

4.讀取數(shù)據(jù)源

? ??????//初始化上下文

? ? ? ? ? ? ?Context cxt=new InitialContext();

? ?????????? DataSource ds=(DataSource)cxt.lookup("java:comp/env/jdbc/news");

? ? ? ? ? ? ?Connection conn=ds.getConnection();


<Resource name="jdbc/news"

? ? ? ? ? ? ? auth="Container"? type="javax.sql.DataSource"? maxActive="100"

? ? ? ? ? ? ? maxIdle="30" maxWait="10000" username="root"? password="root"

? ? ? ? ? ? ? driverClassName="com.mysql.jdbc.Driver"

? ? ? ? ? ? ? url="jdbc:mysql://127.0.0.1:3306/news"/>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容