The spring searches components base for the class annotated with @SpringBootApplication
, reference from Locating the Main Application Class . When I write my own component, I want to be able to use this path as well, but I don't know how to get it.
for example:
@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);
}
}
}
I think this class does what you want:
@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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.