我正在嘗試根據在運行時掃描 Java 注釋中的答案為自定義注釋編寫掃描器。但是,為了加快進程,我只想掃描主包(包含主類及其子包的包)下的類。認為確定包名稱的最簡單方法是從主類。我正在編寫的代碼最終會出現在 Spring Boot 應用程序將使用的庫中。所以我無法知道主類的名稱。有沒有辦法在 Spring Boot 應用程序中在運行時確定主類的名稱?
1 回答

qq_笑_17
TA貢獻1818條經驗 獲得超7個贊
假設你的主類用 注釋@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();
}
}
添加回答
舉報
0/150
提交
取消