Aram Aslanyan
Aram Aslanyan

Reputation: 755

Use spring application as library in non-spring application

I implemented spring-boot application and now I want to use it as a lib for non-spring application. How can I initialize lib classes so autowired dependencies work as expected?Obviously if I create class instance with 'new', all autowired dependencies will be null.

Upvotes: 8

Views: 4167

Answers (2)

cmlonder
cmlonder

Reputation: 2550

I'm not sure how you will handle to wait until the context is fully loaded before you try to access some beans from your Constructor etc. But if you just want to access context without creating components manually try one of those:

1) Simply Inject ApplicationContext

@Inject
private ApplicationContext context;

or

2) Implement ApplicationContextAware

public class ApplicationContext implements ApplicationContextAware {
  private ApplicationContext context;

  @Override
  public void setApplicationContext(ApplicationContext context) {
      this.context = context;
  }

  // just quick example, better to set it to your custom singleton class
  public static ApplicationContext getContext() {
    return context;
  }
}

Then use context.getBean(SomeServiceFromLibrary.class);

Upvotes: 1

Qword
Qword

Reputation: 90

The theory is that you need to instantiate an application context for your Spring Boot dependency to live in, then extract a bean from there and make use of it.

In practice, in your Spring Boot dependency you should have an Application.java class or similar, in which a main method starts the application. Start by adding there a method like this:

public static ApplicationContext initializeContext(final String[] args) {
    return SpringApplication.run(Application.class, args);
}

Next step, in you main application, when you see fit (I'd say during startup but might as well be the first time you need to use your dependency) you need to run this code:

final String[] args = new String[0]; // configure the Spring Boot app as needed
final ApplicationContext context = Application.initializeContext(args); // createSpring application context
final YourBean yourBean = (YourBean)context.getBean("yourBean"); // get a reference of your bean from the application context

From here you can use your beans as you see fit.

Upvotes: 2

Related Questions