import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface JdbcInfo {
String driverClass() default “com.mysql.jdbc.Driver”;
String url();
String username() default “root”;
String password() default “1012”;
}
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
public class JdbcUtils {
@JdbcInfo(url = “jdbc:mysql://localhost:3306/day16”)
public static Connection getConnection() throws Exception{
//获取字节码文件
Class clazz = JdbcUtils.class;
//获取getConnection()
Method method = clazz.getMethod(“getConnection”, null);
if(method.isAnnotationPresent(JdbcInfo.class)){//判断方法上是否有注解
//获取注解
JdbcInfo jdbcInfo = method.getAnnotation(JdbcInfo.class);
//获取四大参数
String driverClass = jdbcInfo.driverClass();
String url = jdbcInfo.url();
String username = jdbcInfo.username();
String password = jdbcInfo.password();
//注册驱动
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, username, password);
//获取连接
return connection;
}
return null;
}
public static void main(String[] args) throws Exception {
System.out.println(getConnection());
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/100805.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...