[英]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.我正在尝试在 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).
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.
结果,当您从 main 方法运行应用程序时,我无法获得 ApplicationContext 并且由 spring 管理的所有 bean 都是 null。
Is that possible to use Spring boot project as a.jar without run main method??是否可以使用 Spring 引导项目作为 a.jar 而不运行主要方法?
public class RetrieveSubscriberType {
public RetrieveSubscriberType() {
ApplicationContext appCtx = ApplicationContextUtils
.getApplicationContext();
this.subscriber = (SubscriberDAOImpl)appCtx.getBean("subscriber");
}
appCtx always null 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;
}
}
ApplicationContextUtils where method setApplicationContext is not called未调用方法 setApplicationContext 的 ApplicationContextUtils
You might need to bootstrap your @Configuration
classes via AnnotationConfigApplicationContext
您可能需要通过
AnnotationConfigApplicationContext
引导您的@Configuration
类
@Configuration
classes are typically bootstrapped using either AnnotationConfigApplicationContext
or its web-capable variant, AnnotationConfigWebApplicationContext
. @Configuration
类通常使用AnnotationConfigApplicationContext
或其支持网络的变体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 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.