Spring 在运行时引导获取 main class 的名称

Spring Boot get name of main class at runtime

我正在尝试根据 Scanning Java annotations at runtime 中的答案为自定义注释编写一个扫描器。

不过,为了加快进程,我只想扫描主包下的classes(包含主class及其子包的包)。认为确定包名称的最简单方法是从主 class.

我正在编写的代码最终会出现在一个库中,该库将被 Spring 引导应用程序使用。所以我无从知道主class的名字。在 Spring 引导应用程序中,有没有办法在运行时确定主要 class 的名称?

此致,

阿诺普

假设您的主要 class 被注释为 @SpringBootApplication,可以使用 ApplicationContext::getBeansWithAnnotation():

来完成
@Service
public class MainClassFinder {

    @Autowired
    private ApplicationContext context;

    public String findBootClass() {
        Map<String, Object> annotatedBeans = context.getBeansWithAnnotation(SpringBootApplication.class);
        return annotatedBeans.isEmpty() ? null : annotatedBeans.values().toArray()[0].getClass().getName();
    }
}