java框架Spring学习(一)

创建一个接口

public interface UserDao {
	
	void printInfo();
}

创建一个类实现该接口

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class UserDaoImpl implements UserDao{
	private String jdbcUrl;
	private String driverClass;
	private String username;
	private String password;
	
	public UserDaoImpl() {
		//读取配置文件
		String resource = "jdbc.properties";
		Properties props = loadProperties(resource);
		
		//初始化信息
		jdbcUrl = props.getProperty("jdbcUrl");
		driverClass = props.getProperty("driverClass");
		username = props.getProperty("username");
		password = props.getProperty("password");
		
		//显示信息
		printInfo();
	}
	
	/**
	 * 加载配置文件
	 * @param resource
	 */
	private Properties loadProperties(String resource){
		InputStream inputStream = null;
		
		try {
			inputStream = getClass().getResourceAsStream(resource);
			/**
			 * 从根目录开始找
			 * this.getClass().getClassLoader().getResourceAsStream("");
			 * 从当前目录开始找
			 * this.getClass().getResourceAsStream("");
			 */
			Properties props = new Properties();
			props.load(inputStream); //读配置文件
			return props;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally{
			try {
				inputStream.close();//关闭流	
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		
	}
	

	public void printInfo(){
		System.out.println("jdbcUrl =  "+jdbcUrl);
		System.out.println("driverClass =  "+driverClass);
		System.out.println("username =  "+username);
		System.out.println("password =  "+password);
	}

	public String getJdbcUrl() {
		return jdbcUrl;
	}

	public void setJdbcUrl(String jdbcUrl) {
		this.jdbcUrl = jdbcUrl;
	}

	public String getDriverClass() {
		return driverClass;
	}

	public void setDriverClass(String driverClass) {
		this.driverClass = driverClass;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}


配置文件jdbc.properties

jdbcUrl      = jdbc:mysql:///test22
driverClass  = com.mysql.jdbc.Driver
username     = root
password     = root


单元测试类

import static org.junit.Assert.*;

import org.junit.Test;

public class UserDaoImplTest {

	@Test
	public void testUserDaoImpl() {
		UserDao userDao = new UserDaoImpl();
	}

}

达到的目的,可以通过修改配置文件来修改内容


你可能感兴趣的:(java框架Spring学习(一))