@RequestScope annotation behaviour with Java inheritance

1.4k Views Asked by At

Lets say we have a class

@RequestScope 
public abstract class A {
    int a;
}

and another class which extends the above class

@Service 
public class B extends A {
    public int getA () { return a; }    
}

Is this class B's variable (that it is extending from A) is a request scoped variable?

UPD

I was going through the spring code, it says

/** * Constant for the default scope name: {@code ""}, equivalent to singleton * status unless overridden from a parent bean definition (if applicable). */ public static final String SCOPE_DEFAULT = "";

Also,

((AbstractBeanDefinition)((AnnotationConfigEmbeddedWebApplicationContext) ctx).
getBeanDefinition("b")).scope

returns "singleton"

but if I mark class B with @RequestScope this property changes to ""
which i assume is sigleton again

1

There are 1 best solutions below

3
On

To be inheritable annotation has to be marked with @Inherited annotation. Take a look at the source code of @RequestScope:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Scope(WebApplicationContext.SCOPE_REQUEST)
public @interface RequestScope {

    /**
     * Alias for {@link Scope#proxyMode}.
     * <p>Defaults to {@link ScopedProxyMode#TARGET_CLASS}.
     */
    @AliasFor(annotation = Scope.class)
    ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;

}

It's not marked with @Inherited. Therefore it doesn't affect subclasses. That means variable of class B from your example is not request scoped but singleton as it's supposed to be by default. You can find more details about predefined annotations here.