【问题标题】:What is role in spring bean?春豆有什么作用?
【发布时间】:2020-12-30 01:08:23
【问题描述】:

我正在学习spring bean。我在BeanDefinition 中发现使用@Role 我们可以将角色添加到bean。但我不明白什么时候申请这个角色。我的意思是这个注释的效果是什么?人们何时以及如何使用此注释?我已阅读文档但无法正确理解

/**
     * Role hint indicating that a {@code BeanDefinition} is a major part
     * of the application. Typically corresponds to a user-defined bean.
     */
    int ROLE_APPLICATION = 0;

    /**
     * Role hint indicating that a {@code BeanDefinition} is a supporting
     * part of some larger configuration, typically an outer
     * {@link org.springframework.beans.factory.parsing.ComponentDefinition}.
     * {@code SUPPORT} beans are considered important enough to be aware
     * of when looking more closely at a particular
     * {@link org.springframework.beans.factory.parsing.ComponentDefinition},
     * but not when looking at the overall configuration of an application.
     */
    int ROLE_SUPPORT = 1;

    /**
     * Role hint indicating that a {@code BeanDefinition} is providing an
     * entirely background role and has no relevance to the end-user. This hint is
     * used when registering beans that are completely part of the internal workings
     * of a {@link org.springframework.beans.factory.parsing.ComponentDefinition}.
     */
    int ROLE_INFRASTRUCTURE = 2;

【问题讨论】:

  • 这用于指示 bean 在应用程序中扮演的“角色”(属于哪个类别)。您很少需要在自己的 bean 上使用 @Role 注释,据我所知,Spring 不会将它用于任何必要的事情。也许它是用来调试的。

标签: java spring spring-boot design-patterns


【解决方案1】:

如 cmets 中所述,它们只是提示用户了解此 bean 实际用途的线索。

一个可能的用例是确保当前在上下文中注册了哪些 bean:

    public static void getBeanRoleInfo(GenericApplicationContext ctx) {

        int[] beanCntByRole = new int[3];
        for (String name : ctx.getBeanDefinitionNames()) {
            int roleNo = ctx.getBeanDefinition(name).getRole();
            beanCntByRole[roleNo]++;
        }

        System.out.println("ROLE_APPLICATION : " + beanCntByRole[0] +
                "\n" + "ROLE_SUPPORT : " + beanCntByRole[1] +
                "\n" + "ROLE_INFRASTRUCTURE : " + beanCntByRole[2]
        );
    }

顺便说一句,Spring 团队没有使用 enum class 的原因是 Spring 的早期版本没有 jdk 1.5 之后可用的 enum class。

如果你想设置,可以使用@Role注解。

【讨论】:

    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    相关资源
    最近更新 更多