Boot在运行时获取主类的名称

Boot在运行时获取主类的名称

本文介绍了Spring Boot在运行时获取主类的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据在以下位置扫描Java注释中的答案来编写用于自定义注释的扫描程序:运行时.

但是,为了加快处理速度,我只想扫描主程序包(具有主类及其子程序包的程序包)下的类.确定最简单的确定包名称的方法是从主类中获取.

However, to speed up the process, I only want to scan the classes under the main package (package which has the main class and its sub-packages). Figured that the easiest way to determine the package name would be from the main class.

我正在编写的代码最终将存储在一个库中,该库将由Spring Boot应用程序使用.因此,我无法知道主类的名称.在Spring Boot应用程序中,是否可以在运行时确定主类的名称?

The code I am writing would end up in a library which will be used by Spring Boot applications. So I have no way of knowing the name of the main class. Is there a way to determine the name of the main class at runtime in Spring Boot application?

此致

Anoop

推荐答案

假设您的主类带有@SpringBootApplication批注,则可以使用 ApplicationContext::getBeansWithAnnotation() :

Assuming your main class is annotated with @SpringBootApplication, it can be done using 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();
    }
}

这篇关于Spring Boot在运行时获取主类的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 01:59