Java spring annotation based AOP exception handling method

1、 Foreword

When the project was just developed, it was not well prepared. When the development reaches a certain level, I will think that there are still some problems that have not been solved. For example, today I want to talk about a problem: exception handling. When writing programs, you usually pass try catch... Finally handle exceptions, but can we really handle all possible exceptions when writing programs? And what logic to execute when an exception occurs, what prompt information to return, and what page to jump to, all these should be considered.

2、 Exception handling based on @ controlleradvice (enhanced controller)

@The methods using @ exceptionhandler, @ initbinder, @ modelattribute annotation inside the controlleradvice annotation are applied to all @ requestmapping annotation methods. In this example, exceptionhandler is used to apply to all @ requestmapping annotation methods to handle exceptions.

Example code:

If it doesn't work, please check the configuration file of spring MVC to see if there is the following configuration of controlleradvice

3、 AOP based exception handling

1. Handle the exception webexceptionaspect in the controller layer java

2. Handle the exception serviceexceptionaspect of the service layer java

3. Usage: add the following configuration to the public configuration file of spring:

Or customize a registration class, serviceexceptionaspect Java and webexceptionaspect Add @ Component annotation to Java

4、 Doubt

@Within (org. Springframework. Stereotype. Service), intercepting all methods of the class annotated with @ service

@Annotation (org. Springframework. Web. Bind. Annotation. Requestmapping) intercepts annotation methods with @ rquestmapping

5、 Testing

Write exception test classes of controller layer and service layer respectively. This is very simple. Just throw an exception in the method. Finally, verify whether the method corresponding to @ afterthrowing is executed when the exception occurs. It depends on the demo I wrote, hey hey!!!

Full project download address: Spring AOP_ jb51. rar

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>