Why Consistent API Responses Matter: A Java Controller & AOP Guide
The article explains common pitfalls in Java API design—such as inconsistent return formats, missing error handling, irrelevant parameters, and improper use of maps or JSON strings—and demonstrates how adopting a unified ResultBean structure together with AOP can improve readability, error management, and testability of backend services.
1. Interface Definition
In daily development we often need to define APIs for system integration and front‑back communication. Inconsistent return formats, missing error handling, irrelevant or overly complex parameters are common problems.
Common Issues
Inconsistent return format : the same endpoint may return an array, a single object, or a plain error string. The article shows a bad example returning Map<String, Object> and suggests using a unified ResultBean (or PageResultBean for pagination).
No failure handling : methods that only return success data force later refactoring when errors appear.
Irrelevant parameters : passing language or userId directly in the method signature instead of obtaining them from the session.
Complex parameters : accepting raw JSON strings or maps reduces readability; a dedicated bean should be defined.
Missing useful return data : create operations should return the new entity’s identifier rather than a boolean.
All the above lead to unreadable code and extra rework.
2. Controller Guidelines
Adopt a unified response type for every controller method:
All methods return ResultBean or PageResultBean.
The response objects are not passed to service layers; services should work with domain beans.
Avoid exposing HttpServletRequest / HttpServletResponse in controller signatures.
Logging is handled in AOP, not directly in controllers.
The article provides a Lombok‑annotated ResultBean implementation with fields code, msg, and generic data, plus static constants for success, failure, no‑login, and no‑permission.
AOP for Controllers
An aspect intercepts all public methods returning ResultBean. It records execution time, logs successful calls, and wraps exceptions into a ResultBean with appropriate error codes. Known exceptions ( CheckException, UnloginException) receive specific codes; unknown exceptions are logged and returned as generic failures.
public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
long startTime = System.currentTimeMillis();
ResultBean<?> result;
try {
result = (ResultBean<?>) pjp.proceed();
logger.info(pjp.getSignature() + " use time:" + (System.currentTimeMillis() - startTime));
} catch (Throwable e) {
result = handlerException(pjp, e);
}
return result;
}The corresponding XML configuration uses aop:aspectj-autoproxy, defines the bean, pointcut, and around advice.
<aop:aspectj-autoproxy/>
<beans:bean id="controllerAop" class="xxx.common.aop.ControllerAOP"/>
<aop:config>
<aop:aspect id="myAop" ref="controllerAop">
<aop:pointcut id="target"
expression="execution(public xxx.common.beans.ResultBean *(..))"/>
<aop:around method="handlerControllerMethod" pointcut-ref="target"/>
</aop:aspect>
</aop:config>Using a consistent ResultBean enables AOP to handle logging and exception wrapping uniformly, improving code readability, testability, and maintainability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
