Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use custom annotation + springAop to realize parameter non-null check

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use custom annotations + springAop to achieve parameter non-empty check", the content of the article is simple and clear, easy to learn and understand, please follow the editor's ideas slowly in-depth, together to study and learn "how to use custom annotations + springAop to achieve parameter non-empty check" bar!

Catalogue

Custom annotation + springAop parameter non-null check

Create a new annotation class @ interface ParamsVerify

Using springAop to realize section

Create a new facet class

Use annotations to uniformly verify that the parameter is not empty

1. Class to be checked

two。 Annotation class

3. Check

Custom annotation + springAop parameter non-null check

Custom annotation to check the input parameters of the corresponding method, and a parameter error is returned if empty

Create a new annotation class @ interface ParamsVerify@Target (ElementType.METHOD) / / enumeration, indicating where the annotation may appear @ Retention (RetentionPolicy.RUNTIME) / / keep the annotation @ Documented// at runtime and you will see this annotation when you generate the api document. You can add or not add public @ Interface ParamsVerify () {/ / the annotation class modifier must be public. If it is not written, it will default to public String [] params () default "; / / the parameter of the incoming method} uses springAop to implement the aspect.

With springAop, we can uniformly handle the operations that need to be repeated in addition to the business core code, such as printing logs, parameter verification, and so on, in an aspect, which is composed of pointcuts and notifications (enhancements).

Enhancement is to add additional logic (code) to the code managed by Aop through dynamic proxies. There are two ways to implement dynamic proxies, one is through jdk, the other is using cglib by default in cglib,springboot, and ponitCut, which is a pointcut composed of multiple connection points, usually points to a defined location in the program through expressions to tell the scope of springAop startup.

/ / this pointcut is defined as any method using the annotation can execute the notification @ Pointcut ("@ annotation (com.xy.utlis.annotations.TestA)") in the facet class to create a new facet class.

Notification method execution order

Surround-front-rear

@ Aspect// declares that the class is a facet class @ Component// declares that the class is handed over to spring management public class testAImpl {/ * * to define pointcuts Use the TestA annotation method * / @ Pointcut ("@ annotation (com.xy.utlis.annotations.TestA)") public void addAdvice () {} @ Aroud ("addAdvice") / / surround notification plus @ Before @ After public Object test (ProceedingJoinPoint joinPoint) throws Throwable {System.out.println ("orbit method starts execution....") / / get all parameter names String [] parameterNames = ((MethodSignature) joinPoint.getSignature ()) .getParameterNames (); / / get all parameter values Object [] args = joinPoint.getArgs (); / / get the method MethodSignature signature = (MethodSignature) joinPoint.getSignature () under the current annotation; Method method = signature.getMethod () / / get annotations TestA annotation = signature.getMethod () .getAnnotation (TestA.class) according to the current method; String [] names = annotation.params (); / / get annotation parameters Map params = params (joinPoint); for (String name: names) {Object o = params.get (name) If (null==o | | ".equals (o)) {System.err.println (MessageFormat.format (" the value of parameter name {0} is null ", name); return false;}} System.out.println (" end of execution around method.... "); return joinPoint.proceed (); / / continue normal execution of method}}

Write an interface to test for success

@ PostMapping ("test") @ TestA (params= {"name", "age", "sex"}) / / indicates that these three parameters are required public void test (String name,String age,String sex) {System.out.println ("ok");}

Send a post request with only name

Detected that the parameter is null, print error message

Here you can customize the return of outliers or other processing.

Request interface with full parameters

Successful release

Use annotations to uniformly verify that the parameter is not empty

Can be modified to make a tool class

Code:

1. Public class User {@ NonNull (content = "name cannot be empty", minLen = 2, maxLen = 100) private String name; public String getName () {return name;} public void setName (String name) {this.name = name;}} 2. Annotation class @ Documented@Target (value = ElementType.FIELD) @ Retention (value = RetentionPolicy.RUNTIME) public @ interface NonNull {String name () default ""; String content () default ""; int maxLen () default 50; int minLen () default 1;} 3. Check public void test () {User user = new User (); user.setName ("Lao Wang"); try {valid (user);} catch (IllegalAccessException e) {e.printStackTrace ();} catch (InvocationTargetException e) {e.printStackTrace () } private void valid (T user) throws IllegalAccessException, InvocationTargetException {Class clazz = user.getClass (); Field [] declaredFields = clazz.getDeclaredFields (); Method [] methods = clazz.getMethods (); for (Field field: declaredFields) {validParams (user, methods, field);} System.out.println ("= parameter check passed =") } private void validParams (T user, Method [] methods, Field field) throws IllegalAccessException, InvocationTargetException {NonNull annotation = field.getAnnotation (NonNull.class); String fieldName; if (StringUtils.isNotBlank (annotation.name () {fieldName = annotation.name ();} else {fieldName = field.getName () } for (Method method: methods) {if (("get" + fieldName) .toLowerCase () .equals (method.getName () .toLowerCase ()) {Object getMethodResult = method.invoke (user, null); if (getMethodResult = = null) {System.out.println ("= non-Null check failure =") Throw new IllegalArgumentException ("[" + annotation.content () + "] is null");} if (getMethodResult instanceof String) {if (StringUtils.isBlank (String.valueOf (getMethodResult) {System.out.println ("= non-null check failure =") Throw new IllegalArgumentException ("[" + annotation.content () + "] is empty");} System.out.println (fieldName + "length:" + String.valueOf (getMethodResult) .length ()) If (String.valueOf (getMethodResult). Length () > annotation.maxLen ()) {System.out.println ("= length exceeds specified range ="); throw new IllegalArgumentException ("[" + fieldName + "] length exceeds") } if (String.valueOf (getMethodResult). Length () < annotation.minLen ()) {System.out.println ("= length less than the specified range ="); throw new IllegalArgumentException ("[" + fieldName + "] is not long enough") }}

Results reference:

Name length: 2

= parameter check passed =

Name length: 2

= length less than the specified range =

Thank you for your reading, the above is the content of "how to use custom annotations + springAop to achieve parameter non-empty check". After the study of this article, I believe you have a deeper understanding of how to use custom annotations + springAop to achieve parameter non-empty check, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report