[英]Run spring boot without @SpringBootApplication annotation as jar library in another project
我正在嘗試在 spring 引導項目中使用 @autowired 注釋,該項目不是由帶有 @SpringBootApplication 注釋的 main 方法啟動的。 Instead, i did created a jar of that spring project and i'm using that jar as an external jar in a legacy project (non-spring project). 結果,當您從 main 方法運行應用程序時,我無法獲得 ApplicationContext 並且由 spring 管理的所有 bean 都是 null。
是否可以使用 Spring 引導項目作為 a.jar 而不運行主要方法?
public class RetrieveSubscriberType {
public RetrieveSubscriberType() {
ApplicationContext appCtx = ApplicationContextUtils
.getApplicationContext();
this.subscriber = (SubscriberDAOImpl)appCtx.getBean("subscriber");
}
appCtx 總是 null
@Configuration
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext appContext)
throws BeansException {
ctx = appContext;
}
public static ApplicationContext getApplicationContext() {
return ctx;
}
}
未調用方法 setApplicationContext 的 ApplicationContextUtils
從提供的文檔
您可能需要通過AnnotationConfigApplicationContext
引導您的@Configuration
類
@Configuration
類通常使用AnnotationConfigApplicationContext
或其支持網絡的變體AnnotationConfigWebApplicationContext
進行引導。
前者的簡單示例如下:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
MyBean myBean = ctx.getBean(MyBean.class);
// use myBean ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.