//餓漢式:
? ? ? ? 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"/>