注解代替框架中的配置文件

博客内容主要提及定义一个注解JdbcInfo,还说明了通过Retention元注解来指定注解的生命周期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.定义一个注解JdbcInfo:
/**

  • 通过Retention元注解,来指定注解的生命周期
    */
@Retention(RetentionPolicy.RUNTIME)
   public @interface JdbcInfo {
   String url();
   String username() default "root";
   String password();
   String driverClass() default "com.mysql.jdbc.Driver";
}

二.

@JdbcInfo(url = "jdbc:mysql:///day17", password = "123")
public class JDBCUtil {
    private static String user;
    private static String password;
    private static String url;
    private static String driverClass;
    static {
        //解析注解,获取注解上的数据
        //1.获取JDBCUtil类上的JdbcInfo注解
        //获取当前类的字节码对象
        Class<JDBCUtil> clazz = JDBCUtil.class;
        JdbcInfo info = clazz.getAnnotation(JdbcInfo.class);//获取JdbcInfo注解

        //获取该注解对象上的所有属性值
        //空指针异常,只有可能是调用方法的对象为空
        url = info.url();
        user = info.username();
        password = info.password();
        driverClass = info.driverClass();
        //1.注册驱动
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取连接对象的方法
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    /**
     * 关闭conn和statement的方法
     * @param conn
     * @param stm
     * @throws SQLException
     */
    public static void close(Connection conn,Statement stm) throws SQLException {
        close(conn,stm,null);
    }

    /**
     * 关闭conn、stm、rst对象
     * @param conn
     * @param stm
     * @param rst
     */
    public static void close(Connection conn, Statement stm, ResultSet rst) throws SQLException {
        if (rst != null) {
            rst.close();
        }
        if(stm != null){
            stm.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
    public static void main(String[] args) throws Exception {
        Connection conn = getConnection();
        System.out.println(conn);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值