properties配置文件——动态配置

 Java 支持的配置文件是 .properties 文件的读写

Properties 类的方法

Properties 类存在于包 Java.util 中,该类继承自 Hashtable ,它提供了几个主要的方法:

  1.  getProperty ( String key) 通过参数 key ,得到 key 所对应的 value。
  2.  load ( InputStream inStream) 从输入流中读取属性列表(键和元素对)。通过对指定的.properties文件进行装载来获取该文件中的所有键值对。
  3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
  4. store ( OutputStream out, String comments) , 以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
  5.  clear () ,清除所有装载的 键 - 值对。该方法在基类中提供。

 转载:http://t.csdn.cn/qQH3S

property文件的存放

IDEA2020.03创建带有Maven的web项目时,propery存放在resource文件夹下。

 

IDEA2020.01web项目时,存放在src文件夹下。

javaWeb项目中的三层模型MVC模型中用到的工厂模式——给dao层和service层的接口映射对应实现类的工厂类

  • dao层和service层使用接口的原因?

满足面向对象设计原则:开闭原则、依赖倒转原则、理氏替换原则。

依赖倒转原则——高层不依赖于低层,二者都依赖于抽象,也就是面向接口编程。

层与层使用接口隔离,为了调用与实现解耦,为了后期的维护。

  • 使用Service接口——是让表示层不依赖于业务层的具体实现。
  • 使用DAO接口——是让业务层不依赖于持久层的具体实现。

mvc : model模型层  control业务层 view表示层

javaWeb经典三层模型:web表示层 service业务层 dao数据持久(访问)层

bean.properties配置文件

注意!value后面不需要写分号 ;

 BeanFactory 工具类

package com.fs.user.util;

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

public class BeanFactory {
    static Properties props = new Properties();
    static {
        //加载property文件
        InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            //对.properties文件进行装载来获取该文件中的所有键值对
            props.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //产生一个Dao的实现类对象
    public static <T> T createBean(Class<T> clazz){
        //反射技术 调用无参构造方法
        String simpleName = clazz.getSimpleName();
        //接口对应的实现类全限定名
        String className = props.getProperty(simpleName);//getProperty通过key找value
        //得到实现类Class对象
        try {
            Class<?> clazz1 = Class.forName(className);
            return (T)clazz1.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

        return null;
    }
}

使用BeanFactory工具类 得到接口对应的实现类

//调用Service层 
IAdminService iAdminService = BeanFactory.createBean(IAdminService.class);
//调用dao层
UserDao userDao = BeanFactory.createBean(UserDao.class);

连接数据库的配置文件

 JDBCUtil工具类

package com.fs.user.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * jdbc工具类
 */
public class JDBCUtil {
   static Properties props = new Properties();
   static{
        //加载db.properties文件
        InputStream in =  JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
       try {
           //加载到Properties集合中
           props.load(in);
           Class.forName(props.getProperty("driverClass"));
       } catch (IOException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
   }

    /**
     * 获取一个连接对象
     * @return
     */
    public static Connection getConnection() throws SQLException {
        return  DriverManager.getConnection(props.getProperty("url"),props.getProperty("username"),props.getProperty("password"));
    }


    /**
     * 关闭资源
     */
    public static void close(ResultSet rs, PreparedStatement pstmt,Connection conn){
        try {
            if(rs != null) rs.close();
            if(pstmt != null) pstmt.close();
            if(conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static PreparedStatement createPreparedStatement(Connection conn,String sql,Object... parms) throws SQLException {
        PreparedStatement pstmt = null;
        pstmt = conn.prepareStatement(sql);
        //给?赋值
        if(parms != null  && parms.length > 0){
            for (int i = 0 ; i <parms.length;i++) {
                pstmt.setObject(i+1,parms[i]);
            }
        }
        return pstmt;
    }
    /**
     * 执行增删改的方法
     * @return
     */
    public static  int executeUpdate(String sql,Object... parms){
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtil.getConnection();
            //jdbc默认是开启自动提交
            //设置为手动提交
            //conn.setAutoCommit(false);
            pstmt =createPreparedStatement(conn,sql,parms);
            int row = pstmt.executeUpdate();
            // 提交事务
           //conn.commit();
            return row;
        } catch (SQLException e) {
            e.printStackTrace();
            //出现异常的时候,回滚事务
            /*try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }*/
        }finally {
            JDBCUtil.close(null,pstmt,conn);
        }
        return 0;
    }

    /**
     * 执行查询的方法
     * @return
     */
    public static <T>  List<T> executeQuery(String sql,Class<T> clazz,Object... parms){
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtil.getConnection();
            pstmt =createPreparedStatement(conn,sql,parms);
            return parseResultSet(pstmt.executeQuery(),clazz);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(null,pstmt,conn);
        }
        return null;
    }

    /**
     * 解析ResultSet
     *   返回值?
     *   参数?
     */
    public static <T> List<T> parseResultSet(ResultSet rs, Class<T> clazz) throws SQLException, IllegalAccessException, InstantiationException {
        List<T>  list = new ArrayList<>();
        if(rs == null){
           return null;
        }
        while(rs.next()){
            //反射
            T t = clazz.newInstance();
            //获取从父类继承的属性
            //1.得到clazz对应的类的父类的Class类型
            Class<? super T> superclass = clazz.getSuperclass();
            //判断父类不是Object
            if(superclass != Object.class){
                Field[] superFields = superclass.getDeclaredFields();
                for (Field field : superFields) {
                    field.setAccessible(true);
                    //约定: 属性名与列名一样: 使用别名
                    field.set(t,rs.getObject(field.getName()));
                    //找set方法赋值
                }
            }
            //获取本类属性
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                //约定: 属性名与列名一样: 使用别名
                //数据库获取的id 类型:  Long   Admin的id Integer
                //  Long  赋值给Integer  错误
                field.set(t,rs.getObject(field.getName()));
                //rs.getInt()
               /* if(field.getType() == String.class){
                    field.set(t,rs.getString(field.getName()));
                }else if(field.getType() == Integer.class){
                    field.set(t,rs.getInt(field.getName()));
                }else if(field.getType() == Double.class){
                    field.set(t,rs.getDouble(field.getName()));
                }*/
                //找set方法赋值
            }

                list.add(t);
        }
        return list;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值