死磕源码系列【ContextIdApplicationContextInitializer源码解析】

拼搏现实的明天。 2022-11-21 03:34 283阅读 0赞

ContextIdApplicationContextInitializer类是ApplicationContextInitializer初始化器接口实现类,会在应用程序启动的时候初始化应用程序的唯一ID。

ContextIdApplicationContextInitializer设置Spring ApplicationContext上下文ID,如果spring.application.name属性存在,则将其作为ID,否则使用application默认值作为ID,源码如下:

  1. public class ContextIdApplicationContextInitializer
  2. implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {
  3. private int order = Ordered.LOWEST_PRECEDENCE - 10;
  4. public void setOrder(int order) {
  5. this.order = order;
  6. }
  7. @Override
  8. public int getOrder() {
  9. return this.order;
  10. }
  11. //初始化器对象回调方法
  12. @Override
  13. public void initialize(ConfigurableApplicationContext applicationContext) {
  14. //获取上下文ID实例
  15. ContextId contextId = getContextId(applicationContext);
  16. //将获取到的ID设置到ApplicationContext上下文中
  17. applicationContext.setId(contextId.getId());
  18. //将上下文ID注入到IOC容器之中
  19. applicationContext.getBeanFactory().registerSingleton(ContextId.class.getName(), contextId);
  20. }
  21. //获取上下文 ID实例对象
  22. private ContextId getContextId(ConfigurableApplicationContext applicationContext) {
  23. ApplicationContext parent = applicationContext.getParent();
  24. if (parent != null && parent.containsBean(ContextId.class.getName())) {
  25. return parent.getBean(ContextId.class).createChildId();
  26. }
  27. return new ContextId(getApplicationId(applicationContext.getEnvironment()));
  28. }
  29. //获取应用程序上下文ID,如果spring.application.name存在,则使用此值,否则使用application
  30. private String getApplicationId(ConfigurableEnvironment environment) {
  31. String name = environment.getProperty("spring.application.name");
  32. return StringUtils.hasText(name) ? name : "application";
  33. }
  34. /** * 上下文ID */
  35. static class ContextId {
  36. private final AtomicLong children = new AtomicLong(0);
  37. private final String id;
  38. ContextId(String id) {
  39. this.id = id;
  40. }
  41. ContextId createChildId() {
  42. return new ContextId(this.id + "-" + this.children.incrementAndGet());
  43. }
  44. String getId() {
  45. return this.id;
  46. }
  47. }
  48. }

GitHub地址:https://github.com/mingyang66/spring-parent

发表评论

表情:
评论列表 (有 0 条评论,283人围观)

还没有评论,来说两句吧...

相关阅读