【问题标题】:@RequestScope annotation behaviour with Java inheritance带有 Java 继承的 @RequestScope 注释行为
【发布时间】:2020-03-21 06:09:45
【问题描述】:

假设我们有一个类

@RequestScope 
public abstract class A {
    int a;
}

以及扩展上述类的另一个类

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

这个类 B 的变量(它从 A 扩展而来)是请求范围的变量吗?

UPD

我正在查看 spring 代码,它说

/** * 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 = "";

还有,

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

返回"singleton"

但如果我用 @RequestScope 标记 B 类,则此属性将更改为 ""
我假设又是sigleton

【问题讨论】:

    标签: spring spring-boot inheritance spring-annotations requestscope


    【解决方案1】:

    要成为可继承的注解必须用@Inherited注解来标记。看看@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;
    
    }
    

    它没有用@Inherited 标记。因此它不会影响子类。这意味着您示例中的 B 类变量不是请求范围的,而是单例的,因为它应该是默认的。您可以找到有关预定义注释 here 的更多详细信息。

    【讨论】:

    • 如果我们看一下lombok getter注解,它也没有用@Inherited注解标记,但似乎可以工作。
    • @swayamraina 因为 lombok getter 注释标记方法,而不是类。子类继承了应用了所有注释的方法。
    • @swayamraina 尝试覆盖子类中标有 lombok getter 的方法,你会看到
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2015-10-01
    • 2010-10-16
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多