What is role in spring bean?

Viewed 844

i am learning about spring bean. I found in BeanDefinition that with @Role we can add role to bean. But i dont understand when to apply the role. I mean what are effects of this annotation? When and how people use this annotation? I have read the docs but could not understand properly

/**
     * 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;
1 Answers

As mentioned in the comments, they are just hints to give users a clue that what this bean is actually intended to.

One possible use-case is to ensure which beans are currently registered in the context:

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

By the way, the reason why the Spring team didn't use enum class is that the early version of Spring doesn't have enum class which is available since jdk 1.5.

You can use @Role annotation if you want to set it.

Related