简体   繁体   中英

Run spring boot without @SpringBootApplication annotation as jar library in another project

I'm trying to use @autowired annotation in a spring boot project that's not started by main method with @SpringBootApplication annotation. 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). As result i can't get ApplicationContext and all beans managed by spring when you run application from main method are null.

Is that possible to use Spring boot project as a.jar without run main method??

public class RetrieveSubscriberType {
    public RetrieveSubscriberType() {
        ApplicationContext appCtx = ApplicationContextUtils
                .getApplicationContext();
        
        this.subscriber = (SubscriberDAOImpl)appCtx.getBean("subscriber");
    }

appCtx always 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;
      }
}

ApplicationContextUtils where method setApplicationContext is not called

From the provided docs

You might need to bootstrap your @Configuration classes via AnnotationConfigApplicationContext

@Configuration classes are typically bootstrapped using either AnnotationConfigApplicationContext or its web-capable variant, AnnotationConfigWebApplicationContext .

A simple example with the former follows:

 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
 ctx.register(AppConfig.class);
 ctx.refresh();
 MyBean myBean = ctx.getBean(MyBean.class);
 // use myBean ...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM