Spring Boot get name of main class at runtime

こ雲淡風輕ζ 提交于 2019-12-25 00:05:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!