如何使用@SpringBootApplication获取类注释

时间:2018-06-28 09:53:00

标签: spring spring-boot

spring搜索组件库以@SpringBootApplication(从Locating the Main Application Class引用)注释的类为基础。 当我编写自己的组件时,我也希望能够使用此路径,但是我不知道如何获得它。

例如:

@SpringBootApplication
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

public static class SomeComponent {
    //I use this to scan my custom annotation
    private String basePackage;

    public SomeComponent(String basePackage) {
        this.basePackage = basePackage;
    }
}

@Configuration
public static class SomeComponentConfiguration {

    @Value("${spring.some-component.base-package:}")
    private String basePackage;

    @Bean
    public SomeComponent someComponent() {
        if (basePackage == null) {
            //TODO how to get the Application.class as default path commonly
            basePackage = Application.class.getPackage().getName();
        }
        return new SomeComponent(basePackage);
    }
}
}

1 个答案:

答案 0 :(得分:1)

我认为这堂课能满足您的要求

@Service
public class ApplicationFinder {

  @Autowired private ApplicationContext context;

  public String findBootClass() {
    Map<String, Object> candidates = context.getBeansWithAnnotation(SpringBootApplication.class);
    return candidates.isEmpty() ? null : candidates.values().toArray()[0].getClass().getName();
  }
}
相关问题