Why Override method could still have annotations of parent method?

Viewed 74

Recently I developed a management system, basically all are CRUD operations, see below:

GET admin/foos
GET admin/foos/{id}
POST admin/foos
PUT admin/foos
DELETE admin/foos/{id} 

In order to reduce development work, I put the common logic in BaseController and concrete Controller extends BaseController, e.g.

public class FooController extends BaseController
public class BarController extends BaseController

It could work successfully, but there is a question: why could extend annotations in method of BaseController but cannot extend annotations in BaseController itself?

@RestController
@Slf4j
public abstract class BaseController

    @GetMapping("/{id}")
    @ApiOperation(value = "detail info", notes = "")
    protected ApiResult detail(@PathVariable String id) {
        // ... 
    }

@RestController
@RequestMapping("admin/bars")
public class BarController extends BaseController{
    @Override
    protected ApiResult detail(String id) {
        return super.detail(id);
    }
}

Why BarController cannot extend @RestController and @Slf4j of BaseController but Override method could extend @GetMapping and @ApiOperation? In my opinion Override method would totally replace the original method, so it should not extend the annotations of parent method.

2 Answers

Override method could extend @GetMapping and @ApiOperation, it is credited to spring framework.

org.springframework.core.annotation.AnnotationsScanner#processMethodHierarchy

for (Method candidateMethod : getBaseTypeMethods(context, sourceClass, classFilter)) {
    if (candidateMethod != null && isOverride(rootMethod, candidateMethod)) {
        result = processMethodAnnotations(context, aggregateIndex[0],
            candidateMethod, processor, classFilter);
        calledProcessor = true;
        if (result != null) {
            return result;
        }
    }
}
Related