//饿汉式:
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;
}
}
将文件变成字节流
InputStream inputStream = ConfigManager.class.getClassLoader().getResourceAsStream(file);
1.单例模式定义
单例模式是一种常用的软件设计模式,其定义是单例对象的类只能允许一个实例存在。
1)properties读取配置文件
配置文件内容:
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数据源配置文件
路径: 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.读取数据源
//初始化上下文
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"/>