【问题标题】:Spring Boot AnnotationConfigEmbeddedWebApplicationContext fail to populate autowired declared fields, which are in dynamic classSpring Boot AnnotationConfigEmbeddedWebApplicationContext 无法填充动态类中的自动装配声明字段
【发布时间】:2018-12-19 04:40:35
【问题描述】:

有一个JUnit测试如下:

内存编译器将一个字符串编译为 on.the.fly.The 报告,其中包含一些 @Autowired 声明的字段,如 reportRepository 等。

一切都按预期工作,动态类报告可以使用自动装配字段实现其功能。

在MVC环境下,使用autowired应用上下文,即AnnotationConfigEmbeddedWebApplicationContext,autowired属性值无法填充。

使用调试,findCandidateNames 方法return [],它应该返回一个包含字段名称的数组,就像在测试环境中一样。请参考相关的源代码并给我一些建议。谢谢。

results =  compiler.compile("Report.java", reportClassString);

Class<?> clazz = compiler.loadClass("on.the.fly.Report", results);

IReport report = (IReport) applicationContext.getAutowireCapableBeanFactory().createBean(clazz);    
report.creatPdf(reportObject);

org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“on.the.fly.AgreementReport”的 bean 时出错: 通过字段表示的不满足的依赖关系 '协议报告属性';嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 符合条件的 bean 类型 'com.lims.api.report.domain.dto.AgreementReportProperties' 可用: 预计至少有 1 个 bean 有资格作为 autowire 候选者。 依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587) 在 org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) 在 com.lims.api.sample.web.controller.AgreementController.downloadPdfFile(AgreementController.java:161) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

【问题讨论】:

    标签: java spring-boot model-view-controller dynamic


    【解决方案1】:

    经过几天的研究,我找到了根本原因。 只需将我自定义的类加载器作为spring上下文类加载器的子类,就可以成功注入依赖。 源代码如下:

    Class clazz = compiler.loadClass("on.the.fly.AgreementReport", 结果,context.getClassLoader());

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 2018-12-19
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 2017-09-07
      • 2019-01-10
      • 2018-12-27
      • 2021-04-02
      相关资源
      最近更新 更多