一、自定义的注解
@Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface jdbcConfig { String ip(); int port() default 3306; String database(); String encoding(); String username(); String password(); }
二、通过反射获取注解信息
@jdbcConfig(ip="127.0.0.1",database="test",encoding="UTF-8",username="root",password="admin") public class AnnotationDButil { static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection() throws SQLException { //通过反射获取注解信息 jdbcConfig annotation = AnnotationDButil.class.getAnnotation(jdbcConfig.class); String ip = annotation.ip(); int port = annotation.port(); String database = annotation.database(); String username = annotation.username(); String password = annotation.password(); String encoding = annotation.encoding(); String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=%s", ip,port,database,encoding); return DriverManager.getConnection(url, username, password); } public static void main(String[] args) { try { Connection c = getConnection(); System.out.println(c); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
原文地址:https://www.cnblogs.com/leduo-zuul/p/10690232.html
时间: 2024-11-09 21:57:56