【问题标题】:Spring Boot get name of main class at runtimeSpring Boot 在运行时获取主类的名称
【发布时间】:2019-03-19 06:11:45
【问题描述】:

我正在尝试根据Scanning Java annotations at runtime 中的答案编写自定义注释扫描器。

但是,为了加快进程,我只想扫描主包下的类(包含主类及其子包的包)。认为确定包名的最简单方法是从主类中。

我正在编写的代码最终会在一个库中,供 Spring Boot 应用程序使用。所以我无法知道主类的名称。有没有办法在 Spring Boot 应用程序运行时确定主类的名称?

问候,

阿努普

【问题讨论】:

    标签: java spring spring-boot annotations java-annotations


    【解决方案1】:

    假设你的主类使用@SpringBootApplication注解,可以使用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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 2017-12-10
      • 2018-08-09
      • 2020-06-29
      相关资源
      最近更新 更多