【问题标题】:Spring project as JAR - all innern autowired variables are null [duplicate]作为 JAR 的 Spring 项目 - 所有内部自动装配变量均为空 [重复]
【发布时间】:2015-08-10 23:23:47
【问题描述】:

我编写了一个 Spring Application TemporalConfigurationService (TCS),它在 Spring Boot 上运行良好。它是基于完整代码的配置,而不是使用 persistence.xml 或 context.xml。现在我想将此 API 用作非 Spring 应用程序中的库。如果我尝试在测试中初始化 TCS...

TemporalConfigurationServiceImpl tcs = new TemporalConfigurationServiceApi()

...所有内部存储库和其他 @Autowired 变量为空。如何在其他项目中重用我的 TemporalConfigurationService?

【问题讨论】:

  • 为什么不应该......你自己创建一个新实例,你必须让spring创建和管理实例。
  • 这可能不是一个好的解决方案,但我认为它应该可以工作。您可以使用 ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml"); 加载 spring 应用程序的上下文。 TemporalConfigurationServiceImpl tcs = context.getBean("theBeanName");
  • 令我惊讶的是,这么多年过去了,仍然很少有人不了解依赖注入的基本知识,并期望所有 DI 的东西在他们使用 new 运算符创建对象时都能正常工作!!!
  • 你需要加载你的应用上下文,然后从中获取你需要的bean。
  • 也许你已经使用 Spring 多年了,我才刚刚开始!我希望 Spring Boot 能做一些“超级魔法”,它可以在没有特定 Spring DI 的情况下工作!

标签: java spring jar spring-boot autowired


【解决方案1】:

这就是我解决问题的方法。因为我的服务是完整的基于代码的配置,我必须扩展我的 ApplicationConfig.java:

@Bean
public TemporalConfigurationServiceImpl temporalConfigurationServiceImpl() {
    return new TemporalConfigurationServiceImpl();
}

现在我可以在其他项目中使用我的 TCS 作为库:

ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
TemporalConfigurationServiceImpl configuration = ctx.getBean(TemporalConfigurationServiceImpl.class);

首先我遇到了一些有线异常,所以我还必须删除我的 Spring Boot Start-class,现在它可以工作了!感谢一些评论员和这个链接:http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm

【讨论】:

  • 您可以只使用 Spring Boot,它会为您执行此操作。
猜你喜欢
  • 2015-07-19
  • 2015-09-14
  • 2015-10-13
  • 2015-12-02
  • 2014-12-06
  • 2016-08-08
  • 2015-07-28
  • 1970-01-01
  • 2014-09-08
相关资源
最近更新 更多