package com.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
*
* @author cong
* 数据库连接注解
*
*/
@Target(value = {FIELD})//Target:此注解用到的地方有TYPE、FIELD、METHOD
@Retention(value = RUNTIME)//注解的运行环境
public @interface CustomConnection {
String url() default "";
String driverClass() default "";
String username() default "";
String password() default "";
}
注解处理
package com.annotation.processor;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;import com.annotation.CustomConnection;
@SuppressWarnings("unchecked")//不显示警告提示
public class CustomAnnotationProcessor {
public static <T> void processor(Class<T> clazz) {
try {
//T t = clazz.newInstance();
T t = null;
Field[] fields = clazz.getDeclaredFields();//获取T对象声明变量Constructor<?>[] constructors = clazz.getDeclaredConstructors();//获取T对象的构造函数,因为构造函数的访问级别问题
for(Constructor<?> constructor : constructors) {
constructor.setAccessible(true);//无论T对象的构造函数是什么访问级别都可以访问其方法
t = (T)constructor.newInstance(new Object[]{});
}for(Field field : fields) {
if(field.isAnnotationPresent(CustomConnection.class)) {
CustomConnection customConnection = field.getAnnotation(CustomConnection.class);
String url = customConnection.url();
String driverClass = customConnection.driverClass();
String username = customConnection.username();
String password = customConnection.password();
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, username, password);
field.setAccessible(true);
field.set(t, connection);
continue;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.util;import java.sql.Connection;
import com.annotation.CustomConnection;
/**
*
* @author Administrator
* 调用注解连接数据库
*
*/
public class DBUtil {private DBUtil() {//构造方法
}
@CustomConnection(url = "jdbc:oracle:thin:@//192.168.40.29:1521/PDBMYORACLE",
driverClass = "oracle.jdbc.driver.OracleDriver",
username = "victop",
password = "victop")
private static Connection connection;public static Connection getConnection() {
return connection;
}
}
测试
package com.victop;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;import com.annotation.processor.CustomAnnotationProcessor;
import com.util.DBUtil;public class Test {
public static void main(String[] args) {
try {
CustomAnnotationProcessor.processor(DBUtil.class);
Connection connection = DBUtil.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select * from Users");
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
System.out.println(resultSet.getString("username"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}}
注解实例