annotations

Java currently has only three standard annotations built in

There are four types of meta-annotations, which are dedicated to annotating other annotations

How do I get the value of an annotation at run time? Java implements AnnotatedElement in the Java.lang. reflect package, Class, Method, Field, etc., which provides methods to get the information we need, and the array returned by the Method can be modified by the caller. Without affecting the array returned to other callers.

Method that is part of the AnnotatedElement interface

The interface is named after getDeclared** in java.lang.Class which means to get your own things and the get method which means to get your own and parent things

use

@target (elementtype.field) @Retention(retentionPolicy.runtime) public @interface FruitName { String value() default ""; String alias() default ""; } public enum Color { BLUE, RED, GREEN } @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface FruitColor { Color fruitColor()  default Color.GREEN; }Copy the code

The test class

Public class Apple {// If you just want to assign value, you can use the following shortcuts: // @fruitName (" Apple ") @fruitName (value = "apple", alias = "iPhone ") Private String Name; @FruitColor(fruitColor = Color.RED) private String color; public static void main(String[] args) { Field[] fields = Apple.class.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(FruitName.class)) { FruitName fruitName = (FruitName) field.getAnnotation(FruitName.class); // fruitName is apple System.out.println("fruitName is " + fruitName.value()); // alias is iphone System.out.println("alias is " + fruitName.alias()); } else if (field.isAnnotationPresent(FruitColor.class)) { FruitColor fruitColor = (FruitColor) field.getAnnotation(FruitColor.class); // fruitColor is RED System.out.println("fruitColor is " + fruitColor.fruitColor().name()); }}}}Copy the code

Custom annotation + interceptor to achieve permission management

Custom annotations are usually used for logging, permission management, and configuring dynamic data sources. Custom annotations are also used in conjunction with AOP to perform dynamic repository cutting

I wrote a small Demo with custom annotations and interceptors for permission management, using the Spring Boot framework

Define permission annotations

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Authority {

 String value() default "admin";

}
Copy the code

Adding interceptors

public class AuthorityInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); Authority authority = method.getAnnotation(Authority.class); If (authority == null) {// If (authority == null) {return true; } // If the user logs in for the first time and puts the information into the session, the user will retrieve the session from the Request for each subsequent operation. Get the user information in the session / / and then according to user's information from the database to check permissions String userAuthority. = it getParameter (" userAuthority "); if (! UserAuthority. Equals (" admin ")) {/ / out of the return process of Spring MVC recoding httpServletResponse. SetCharacterEncoding (" utf-8 "); httpServletResponse.setContentType("application/json; charset=UTF-8"); PrintWriter out = httpServletResponse.getWriter(); Out. print(" no permissions "); out.flush(); out.close(); return false; } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }Copy the code

Configuring interceptors

@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new AuthorityInterceptor()).addPathPatterns("/**"); }}Copy the code

Test Controller

@restController Public class UserController {// This is to test if there are no annotations, @requestMapping (value = "login", method = requestmethod.get) public Map login() {Map<String, String> map = new HashMap<>(); map.put("msg", "login success"); return map; } @Authority() @RequestMapping(value = "queryAllProduct", method = RequestMethod.GET) public Map queryAllProduct() { Map<String, String> map = new HashMap<>(); map.put("msg", "this is all data"); return map; }}Copy the code

test