zhuguowei
zhuguowei

Reputation: 8487

Why Override method could still have annotations of parent method?

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.

Upvotes: 3

Views: 114

Answers (2)

zhuguowei
zhuguowei

Reputation: 8487

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;
        }
    }
}

Upvotes: 1

Rabhi salim
Rabhi salim

Reputation: 506

@RestController and @Slf4j are class based annotations while @GetMapping and @ApiOperation are method based annotation which was overridden by @Override.

More detailed info : https://javaee.github.io/javaee-spec/AnnotationRules

Upvotes: 2

Related Questions