Eureka源码解析

1.SpringBoot中的自动装载

1.1 ImportSelector

ImportSelector接口是Spring导入外部配置的核心接口,在SpringBoot的自动化配置和@EnableXXX(功能性注解)中起到了决定性的作用。当在@Configuration标注的CLass上使用@Import引入了一个ImportSelector实现类后,会把实现中返回的Class名称都定义为bean.

package org.springframework.context.annotation;

import org.springframework.core.type.AnnotationMetadata;

public interface ImportSelector {
  String[] selectImports(AnnotationMetadata var1);
}

DeferredImportSelector接口继承ImportSelector,他和ImportSelector的区别在于装载bean的时机上,DeferredImportSelector需要等所有的@Configuration都执行完毕后才会进行装载;
代码如下:

@Data
public class User {

    private String username;
    private Integer age;
}

public class UserConfiguration {

    @Bean
    public User getUser(){
        User user = new User();
        user.setUsername("ABC");
        user.setAge(123);
        return user;
    }

}

public class UserImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        //获取配置类的名称
        return new String[]{UserConfiguration.class.getName()};
    }
}

定义注解:

package com.yxkj.bean;

import org.springframework.context.annotation.Import;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.TYPE)
@Import(UserImportSelector.class)
public @interface EnableUserBean {
}

启动类:

@EnableUserBean
public class TestApplication {
    public static void main(String[] args) {
        //获取spring容器
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestApplication.class);
        User user = ac.getBean(User.class);
        System.out.println(user);
    }
}

装载过程:
image

eureka server启动流程:
image

posted @ 2021-06-26 18:37  风飘落叶  阅读(46)  评论(0编辑  收藏  举报