问题描述
我正在尝试根据 Scanning Java annotations at运行时.
但是,为了加快进程,我只想扫描主包(包含主类及其子包的包)下的类.认为确定包名称的最简单方法是从主类.
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?
问候,
阿努普
推荐答案
假设您的主类使用 @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 在运行时获取主类的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!