簡體   English   中英

在另一個項目中運行 spring 引導而不使用 @SpringBootApplication 注釋作為 jar 庫

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM