[英]Run spring boot without @SpringBootApplication annotation as jar library in another project
我正在尝试在 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). 结果,当您从 main 方法运行应用程序时,我无法获得 ApplicationContext 并且由 spring 管理的所有 bean 都是 null。
是否可以使用 Spring 引导项目作为 a.jar 而不运行主要方法?
public class RetrieveSubscriberType {
public RetrieveSubscriberType() {
ApplicationContext appCtx = ApplicationContextUtils
.getApplicationContext();
this.subscriber = (SubscriberDAOImpl)appCtx.getBean("subscriber");
}
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;
}
}
未调用方法 setApplicationContext 的 ApplicationContextUtils
从提供的文档
您可能需要通过AnnotationConfigApplicationContext
引导您的@Configuration
类
@Configuration
类通常使用AnnotationConfigApplicationContext
或其支持网络的变体AnnotationConfigWebApplicationContext
进行引导。
前者的简单示例如下:
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.