Java Annotation and custom Annotation explanation, javaannotation
I. Introduction to Java annotations
Annotations are often used during development, and user-defined annotations are occasionally seen in projects. Today we will discuss what this annotation is, the application scenarios of annotations, and how to customize annotations.
The following lists common annotations in development.
@ Override: used to identify that the method inherits from the superclass. When the method of the parent class is deleted or modified, the compiler will prompt an error message (the toString (we often see () this product can always be seen in the method)
@ Deprecated: indicates this class or this method is no longer recommended and has expired. If you still want to use it, a compilation warning will be generated.
@ SuppressWarnings: indicates the warning information of the ignored compiler.
Junit Test: @ Test
Some Annotations of Spring: @ Controller, @ RequestMapping, @ RequestParam, @ ResponseBody, @ Service, @ Component, @ Repository, @ Resource, @ Autowire
Java verification annotation: @ NotNull, @ Email
The following describes the true meaning of Override. java.
@Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public @interface Override {}
Ii. Basic Java annotation knowledge
1. Java annotation Data Type
Annotations are written in. in the java file, @ interface is used as the keyword, so the Annotation is also a data type of Java. from a wide range of definitions, Class, Interface, Enum, Annotation all belong to the Class type.
2. Java Metadata Annotation
When creating annotations, you need to use some annotations to describe the annotations you have created, that is, those annotations written on @ interface. These annotations are called meta annotations, for example, @ Target and @ Retention in Override. Some metadata annotations are listed below
@ Brief ented: used to mark whether the annotation is included when javadoc is generated. You can see that this annotation is the same as @ Override, and there is nothing in the annotation.
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Documented {}
@ Target: defines where annotations can be used. By default, annotations can be used anywhere or within a specified range. Annotations are used in classes (such as @ Controller) in development), fields (such as @ Autowire), methods (such as @ RequestMapping), and method parameters (such as @ RequestParam.
TYPE: Class, interface, or enum Declaration
FIELD: FIELD (attribute) Declaration
METHOD: METHOD declaration
PARAMETER: PARAMETER Declaration
CONSTRUCTOR: CONSTRUCTOR
LOCAL_VARIABLE: local variable Declaration
ANNOTATION_TYPE: annotation type declaration
PACKAGE: PACKAGE Declaration
Target. java
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Target { /** * Returns an array of the kinds of elements an annotation type * can be applied to. * @return an array of the kinds of elements an annotation type * can be applied to */ ElementType[] value();}
public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ TYPE, /** Field declaration (includes enum constants) */ FIELD, /** Method declaration */ METHOD, /** Formal parameter declaration */ PARAMETER, /** Constructor declaration */ CONSTRUCTOR, /** Local variable declaration */ LOCAL_VARIABLE, /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE, /** Type parameter declaration */ TYPE_PARAMETER, /** Use of a type */ TYPE_USE}
@ Inherited: Allows subclass to inherit the annotation in the parent class. You can obtain the annotation of the parent class through reflection.
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Inherited {}
@ Constraint: used to verify whether the property value is valid
@Documented@Target({ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface Constraint { Class<? extends ConstraintValidator<?, ?>>[] validatedBy();}
@ Retention: annotation declaration cycle, used to define the annotation survival stage, which can survive at the source code level, compilation level (bytecode level), runtime level
SOURCE: SOURCE Code level. The annotation only exists in the SOURCE code. It is generally used to interact with the compiler and detect the code. For example, @ Override and @ SuppressWarings.
CLASS: bytecode level. Annotations exist in source code and bytecode files. They are mainly used to generate additional files during compilation, such as XML and Java files, but cannot be obtained during runtime. For example, if mybatis generates an object and a ing file, you need to add a Java agent during JVM loading at this level and use the agent to dynamically modify the bytecode file.
RUNTIME: RUNTIME level. Annotations exist in the source code, bytecode, and Java virtual machine. They are mainly used for RUNTIME. reflection can be used to obtain relevant information.
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Retention { /** * Returns the retention policy. * @return the retention policy */ RetentionPolicy value();}
3. Java annotation content
In the above annotation source code, we can see that some annotations do not have any content, and some annotations have content, which looks like a method.
Syntax format of the content of the annotation: default Value of the Data Type attribute name (). The data type is used to describe the data type of the attribute. The default value indicates that the default value is used when the attribute is not assigned a value, generally, the String uses an empty String "" as the default value, and the array uses an empty array {} as the default value.
Next, let's take a look at the Declaration of the RequestMapping annotation in SpringMVC.
@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Mappingpublic @interface RequestMapping { String name() default ""; @AliasFor("path") String[] value() default {}; @AliasFor("value") String[] path() default {}; RequestMethod[] method() default {}; String[] params() default {}; String[] headers() default {}; String[] consumes() default {}; String[] produces() default {};}
Use the RequestMapping annotation in SpringMVC
@RequestMapping(value = "/list", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})public String list(){}
4. annotation application scenarios
You can analyze the application scenarios of annotations through the annotation declaration cycle:
SOURCE code level: used by compilers, such as @ Override and @ Deprecated. There are not many scenarios for developers to use.
CLASS: bytecode level, which is rarely seen
RUNTIME: RUNTIME level, which is the most common. Almost all annotations used by developers are RUNTIME level. RUNTIME annotations are commonly used in the following situations:
Annotation without any attribute, empty annotation. This annotation usually serves as a annotation, such as @ Test, @ Before, @ After, perform some special logic processing by obtaining these tag annotations
You can use the Constraint annotation @ Constraint to verify the attribute values, such as @ Email and @ NotNull.
You can configure some parameters by using attributes in annotations, and then obtain these parameters using reflection. These annotations have no other special functions, it simply replaces the xml configuration to configure some parameters. Using annotations to configure parameters is popular in Spring boot, such as @ Configuration
For the configuration method xml vs annotation, xml is generally used to configure some configuration that is not closely related to the business, and annotations are used to configure some parameters closely related to the business.
III. Basic APIs for Java annotation and reflection
// Obtain the public <A extends Annotation> A getAnnotation (Class <A> annotationClass) Annotation of A certain type; // obtain all annotations (including annotations modified by Inherited in the parent Class) public Annotation [] getAnnotations (); // obtain the declared Annotation (but does not include the Annotation modified by Inherited in the parent class) public Annotation [] getDeclaredAnnotations (); // determine whether an object is marked with a public boolean isAnnotationPresent (Class <? Extends Annotation> annotationClass) // obtain all fields declared by a class, public Field [] getDeclaredFields () throws SecurityException; // obtain a Method, public Method getMethod (String name, class <?>... ParameterTypes );
Iv. Custom annotations
You can use custom annotations, interceptors, or AOP to control permissions.
The following is an example of how to define an annotation to restrict logon when a user accesses an interface.
Step 1: Define annotations
RequiresLogin. java
@Documented@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface RequiresLogin {}
Step 2: Use annotations
@Controller@RequestMapping("/user")public class UserController { @RequiresLogin @RequestMapping(value = "/list", produces = {"application/json;charset=UTF-8;"}) public String getUserList(){ System.out.println("--------------"); return "[{'id': 1, 'username':'zhangsan'}]"; }}
Step 3: Use AOP to intercept and parse annotations
Public class LoginAdvices {public void before (JoinPoint joinPoint) throws Exception {Object target = joinPoint. getTarget (); String methodName = joinPoint. getSignature (). getName (); System. out. println (target + "-------" + methodName); Method method = target. getClass (). getMethod (methodName); boolean annotationPresent = method. isAnnotationPresent (RequiresLogin. class); if (annotationPresent) {// The user must log on Boolean isLogin = false; if (! IsLogin) {throw new Exception ("You must log on to this interface first");} else {System. out. println ("logged on ...");}}}}
Configure aop in applicationContext. xml
<Bean id = "loginAdvices" class = "com. mengdee. manager. aop. LoginAdvices"/> <! -- Aop configuration --> <aop: config proxy-target-class = "true"> <! -- Cut --> <aop: aspect ref = "loginAdvices"> <! -- Cut --> <aop: pointcut id = "pointcut1" expression = "execution (* com. mengdee. manager. controller. *. * (...)"/> <! -- Connect the notification method and cut point --> <aop: before method = "before" pointcut-ref = "pointcut1"/> </aop: aspect> </aop: config>
Custom exception
Why is a custom exception required?
Although Java provides rich exception handling classes, custom exceptions are often used in projects, the main reason is that the exception classes provided by Java still cannot meet various business needs in some cases. For example, some errors in the system conform to the Java syntax but do not conform to the business logic. If the account does not exist when you log on, or the account is locked, you can customize an account exception AccountException.
Or in some cases, the same Java exception may be caused by multiple causes, and it is not easy to locate the error during troubleshooting. In this case, you can use a custom exception.
Benefits of custom exceptions: Custom exceptions can make the exceptions clearer and hide the underlying exceptions, which is safer and more intuitive.
Use of custom exceptions: Custom exceptions generally inherit from Exception or RuntimeException. Some attributes can be used as parameters of the constructor according to business requirements. A programmer needs to manually throw an Exception for a custom Exception, and handle exceptions.
The following is an example of a custom exception in Apache Shiro.
public class ShiroException extends RuntimeException { public ShiroException() { } public ShiroException(String message) { super(message); } public ShiroException(Throwable cause) { super(cause); } public ShiroException(String message, Throwable cause) { super(message, cause); }}
The above is a detailed description of the Java Annotation and custom Annotation.