java框架Spring学习(一)
2015-10-08 22:11
253 查看
创建一个接口
创建一个类实现该接口
配置文件jdbc.properties
单元测试类
达到的目的,可以通过修改配置文件来修改内容
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的类
- java生成随机验证码
- SAX和Dom解析XML的区别
- Java:调用构造器的具体处理步骤
- MyEclipse10.6 myeclipse2013下添加jadClipse反编译插件 .
- Spring学习(一)
- JAVA简单学习
- Java知识点总结
- Java并发编程:Callable、Future和FutureTask
- 在eclipse中集成SVN插件
- 大龄屌丝自学笔记--Java零基础到菜鸟--030
- JAVA语言规范和API网址
- LeetCode118 LeetCode119 LeetCode151 LeetCode202 Java
- Spring验证、数据绑定和类型转换
- Java 和Java虚拟机的关系
- java选择题
- Java体系结构简介
- Java中ArrayList内存分配问题
- 南阳oj A+BproblemII Java 解决 题目103
- spring中配置EventBus