首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >spring bean中的角色是什么?

spring bean中的角色是什么?
EN

Stack Overflow用户
提问于 2020-09-11 21:39:27
回答 1查看 478关注 0票数 3

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

代码语言:javascript
运行
复制
/**
     * 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;
EN

回答 1

Stack Overflow用户

发布于 2021-05-25 16:06:33

正如评论中提到的,它们只是给用户一个线索,让用户知道这个bean的实际用途。

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

代码语言:javascript
运行
复制
    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类的原因是,Spring的早期版本没有从jdk 1.5开始提供的enum类。

如果想要设置,可以使用@Role注释。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63848254

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档