我正在学习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;
发布于 2021-05-25 16:06:33
正如评论中提到的,它们只是给用户一个线索,让用户知道这个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类的原因是,Spring的早期版本没有从jdk 1.5开始提供的enum类。
如果想要设置,可以使用@Role
注释。
https://stackoverflow.com/questions/63848254
复制相似问题