一、自定义的注解
@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(); } } }
三、基本注解详解
@Target表示注解能放在什么位置上
ElementType.TYPE:能修饰类、接口或枚举类型
ElementType.FIELD:能修饰成员变量
ElementType.METHOD:能修饰方法
ElementType.PARAMETER:能修饰参数
ElementType.CONSTRUCTOR:能修饰构造器
ElementType.LOCAL_VARIABLE:能修饰局部变量
ElementType.ANNOTATION_TYPE:能修饰注解
ElementType.PACKAGE:能修饰包
@Retention 表示生命周期
自定义注解@JDBCConfig 上的值是 RetentionPolicy.RUNTIME, 表示可以在运行的时候依然可以使用。 @Retention可选的值有3个:
RetentionPolicy.SOURCE: 注解只在源代码中存在,编译成class之后,就没了。@Override 就是这种注解。
RetentionPolicy.CLASS: 注解在java文件编程成.class文件后,依然存在,但是运行起来后就没了。@Retention的默认值,即当没有显式指定@Retention的时候,就会是这种类型。
RetentionPolicy.RUNTIME: 注解在运行起来之后依然存在,程序可以通过反射获取这些信息,自定义注解@JDBCConfig 就是这样。
@Inherited 表示该注解具有继承性。
@Documented
在用javadoc命令生成API文档后,该类的文档里会出现该注解说明。
@Repeatable 在一个类中可重复的使用一个注解(需要其他注解制定)