在非Spring应用程序中将spring应用程序用作库

Ara*_*yan 5 spring dependency-injection spring-boot

我实现了spring-boot应用程序,现在我想将其用作非spring应用程序的库。我如何初始化lib类以使自动装配的依赖项按预期方式工作?显然,如果我使用“ new”创建类实例,则所有自动装配的依赖项都将为null。

小智 2

理论上来说,您需要为 Spring Boot 依赖项实例化一个应用程序上下文,然后从那里提取一个 bean 并使用它。

实际上,在 Spring Boot 依赖项中,您应该有一个Application.java类或类似的类,其中的 main 方法启动应用程序。首先添加一个像这样的方法:

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

下一步,在您的主应用程序中,当您认为合适时(我想说在启动期间,但也可能是您第一次需要使用依赖项),您需要运行以下代码:

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
Run Code Online (Sandbox Code Playgroud)

从这里您可以根据需要使用您的豆子。