Spring Boot get name of main class at runtime

2019-09-02 19:59发布

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条回答
姐就是有狂的资本
2楼-- · 2019-09-02 20:41

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();
    }
}
查看更多
登录 后发表回答