Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 210
Aram Aslanyan Avatar asked Jun 17 '15 20:06

Aram Aslanyan


People also ask

Can we use spring boot for non Spring application?

The application can also be called as Spring Boot Standalone application. To develop a non web application, your Application needs to implement CommandLineRunner interface along with its run method. This run method acts like a main of your application.

How do I get Spring bean in non Spring class?

getUserService() method simply returns the fetched Spring bean instance of UserService class with this static method. Note that you can call any Spring managed bean here by simply passing the getBean(...) method the class for said bean. E.g.

Is spring boot standalone application?

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need minimal Spring configuration.

Which injection is not supported by Spring?

Spring will only inject Autowired fields in Spring managed beans. AKA if you are using new LoginView() Spring cannot inject dependencies. If you can't let Spring manage that class, you'll need to design it a different way. I'd recommend you use constructor injection instead of field injection, by the way.


1 Answers

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.

like image 161
Qword Avatar answered Sep 30 '22 07:09

Qword