SpringBoot:输出当前工程自动装配类和排除类信息

2年前 (2022) 程序员胖胖胖虎阿
161 0 0

1.原理

利用自定义AutoConfigurationImportListener来实现。

1.1 创建自定义AutoConfigurationImportListener

public class DefaultAutoConfigurationImportListener implements AutoConfigurationImportListener {
    @Override
    public void onAutoConfigurationImportEvent(AutoConfigurationImportEvent event) {
        // Acquire current ClassLoader
        ClassLoader classLoader = event.getClass().getClassLoader();
        // Candidate autoconfig list
        List<String> candidates =
                SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, classLoader);
        // Actual config class list
        List<String> configurations = event.getCandidateConfigurations();
        // Exclude class list
        Set<String> exclusions = event.getExclusions();
        // Print info
        System.out.printf("Autoconfig Class list - Candidate Num: %d, actual Num: %d, exclusion num: %s\n",
                candidates.size(), configurations.size(), exclusions.size());
        // Print actual and exclusion class list
        System.out.println("Actual config class list: ");
        event.getCandidateConfigurations().forEach(System.out::println);
        System.out.println("Exclusion class list: ");
        event.getExclusions().forEach(System.out::println);
    }
}

1.2 新建配置文件resources/META-INF/spring.factories

# Auto Configuration Import Listeners Self Implement
org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
xxx.yyy.DefaultAutoConfigurationImportListener #此处是你本地自定义类的权限类名

1.3 创建引导启动类

// 此处排除RestTemplate自动配置类,测试后面是否会打印出来
@EnableAutoConfiguration(exclude = RestTemplateAutoConfiguration.class)
public class EnableAutoConfigurationBootstrap {
    public static void main(String[] args) {
        new SpringApplicationBuilder(EnableAutoConfigurationBootstrap.class)
                .web(WebApplicationType.NONE)// non-web app
                .run(args)
                .close();// close current context
    }
}

2.测试结果

// 结果
Autoconfig Class list - Candidate Num: 127, actual Num: 25, exclusion num: 1
Actual config class list:
...
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration
Exclusion class list:
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration

相关文章

暂无评论

暂无评论...