Anoop
Anoop

Reputation: 913

Spring Boot get name of main class at runtime

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

Upvotes: 2

Views: 3761

Answers (2)

user213769
user213769

Reputation: 688

If your main app class has @SpringBootApplication annotation and you only want the class name (not Class, not full name for the package name etc.), you can inject any ListableBeanFactory instance you want (e.g. ApplicationContext) to use getBeanNamesForAnnotation() method:

    @Autowired
    private ApplicationContext applicationContext; // or ListableBeanFactory listableBeanFactory etc.

    public String getApplicationClassName() {
        return applicationContext.getBeanNamesForAnnotation(SpringBootApplication::class.java)[0];    
    }

You can also get the application bean itself via getBeansWithAnnotation etc. if you so desire.

Upvotes: 0

syntagma
syntagma

Reputation: 24334

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();
    }
}

Upvotes: 5

Related Questions