我们如何创建新的主键呢?得使用JDK引入的注解(如:@Target:作用域、@Retention:生命周期)
先对这两个注解入个门,直接上源码:
@Target
@Documented //生成javadoc包含注解
@Retention(RetentionPolicy.RUNTIME) //运行时
@Target({ ElementType.ANNOTATION_TYPE }) //作用于注解类型,所以Target是作用于注解上的
public @interface Target {
ElementType[] value();//ElementType 枚举类,作用域
}
查看ElementType:
public enum ElementType {//元素类型
TYPE, //类、接口(包括注解类型)或枚举声明
FIELD, // 字段声明(包括枚举常量)
METHOD, //方法声明
PARAMETER, // 参数声明
CONSTRUCTOR, //构造方法声明
LOCAL_VARIABLE, //局部变量声明
ANNOTATION_TYPE, //注解类型声明
PACKAGE, //包声明
TYPE_PARAMETER,
TYPE_USE;
}
@Retention:
@Documented //javadoc 包含
@Retention(RetentionPolicy.RUNTIME) //运行时
@Target({ ElementType.ANNOTATION_TYPE }) //作用注解类型
public @interface Retention {
RetentionPolicy value();
}
查看枚举类RetentionPolicy:
public enum RetentionPolicy {
SOURCE,//编译器丢弃
CLASS, //class文件可用,VM丢弃
RUNTIME;//VM将在运行期间保留,通过反射机制读取该注解的信息
}
现在开始定义一个新注解
做一个Boy注解:
@Target(ElementType.METHOD) //作用域方法
@Retention(RetentionPolicy.RUNTIME) //运行时
public @interface Boy {
String sex() default "male"; //boy 性别 男
String game() ; //爱玩的游戏
}
调用:
//日志打印
private final static Logger logger =LoggerFactory.getLogger(TestCommon.class);
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
TestCommon t = new TestCommon();
//反射获取hello方法
Method method = t.getClass().getDeclaredMethod("hello", String.class);
//获取该方法上的所有注解
Annotation[] annotation = method.getAnnotations();
for (Annotation annotation2 : annotation) {
//日志打印,其中强制类型转换才能取得到该注解下的方法
logger.info("boy is {} , he love {}",((Boy) annotation2).sex(),((Boy) annotation2).game());
}
}
@Boy(game = "LOL")
String hello(String like) {//使用注解的方法
return "hello";
}
输出结果:
22:21:07.644 [main] INFO com.ecit.lyy.TestCommon - boy is male , he love LOL
拓展:另外,我们使用logback来打印日志信息
所以在pom文件中需要配置:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version>
<scope>compile</scope>
</dependency>
还有,顺便通过pom插件 ,将jdk也改了
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<compilerArguments>
<extdirs>${project.basedir}/src/main/webapp/WEB-INF/lib</extdirs>
</compilerArguments>
</configuration>
</plugin>
</plugins>
</build>