13.1新建一个数据库实体类;
package com.eduask.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
//数据库的实体类;
public class Demo2 {
private static String url;
private static String user;
private static String pwd;
private static String driverClass;
public static Connection getconn(){
Connection conn=null;
try {
conn=DriverManager.getConnection(url, user, pwd);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
try {
Class.forName(driverClass);
this.driverClass = driverClass;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public String toString() {
return "Demo2 \n[url=" + url + "]\n[user=" + user + "]\n[pwd=" + pwd
+ "]\n[driverClass=" + driverClass + "]";
}
public Demo2(String url, String user, String pwd, String driverClass) {
super();
this.url = url;
this.user = user;
this.pwd = pwd;
this.driverClass = driverClass;
}
public Demo2() {
super();
// TODO Auto-generated constructor stub
}
}
13.2 新建一个TestDemo1的测试类;
package com.eduask.util;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDemo2 {
public static void main(String[] args) {
ClassPathXmlApplicationContext cx=new ClassPathXmlApplicationContext("util/demo2.xml");
Demo2 demo2=(Demo2) cx.getBean("demo2");
System.out.println(demo2);
}
}
13.3 新建一个config的源文件下的db.properties
url=jdbc:oracle:thin:@localhost:1521/orcl
user=scott
pwd=tiger
driverClass=oracle.jdbc.driver.OracleDriver
13.4 新建一个demo2.xml的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
">
<context:property-placeholder location="classpath:db.properties"/>
<bean id="demo2" class="com.eduask.util.Demo2"
p:url="${url}"
p:user="${user}"
p:pwd="${pwd}"
p:driverClass="${driverClass}"
/>
</beans>
13.5 程序运行如下:
Demo2
[url=jdbc:oracle:thin:@localhost:1521/orcl]
[user=scott]
[pwd=tiger]
[driverClass=oracle.jdbc.driver.OracleDriver]