问题
I am trying to write a scanner for custom annotations based on the answer in Scanning Java annotations at runtime.
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.
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?
Regards,
Anoop
回答1:
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();
}
}
来源:https://stackoverflow.com/questions/52806176/spring-boot-get-name-of-main-class-at-runtime