【问题标题】:NullPointerException when autowiring into non-spring managed class (POJO) - Spring Boot自动装配到非弹簧托管类(POJO)时出现 NullPointerException - Spring Boot
【发布时间】:2017-06-04 18:38:40
【问题描述】:

我对 Spring Boot 和依赖注入总体上还是比较陌生,所以请原谅这里发生的任何菜鸟问题。我正在构建一个 API,在将依赖项注入 POJO 资源 (DTO) 时遇到问题。

当我在 POJO this.numComments = commentSvc.getAllForPhoto(this.getId()); 中调用该方法时,我得到了 NullPointerException。但是,当我从另一个 spring 管理的 bean 执行此操作并将值传递给构造函数时,它可以正常工作。

阅读后,我似乎需要对 aspectJ 和 Load Time Weaving 做一些事情,但我不确定在我的代码中会是什么样子。

本质上,我的方法看起来像这样:

PhotoResource.java (POJO)

public class PhotoResource extends BaseRepresentable {

   @Autowired
   CommentService commentSvc;

   private Long id;
   private Integer numComments;

   PhotoResource(PhotoEntity entity){
   super(entity);
   this.setId(entity.getId);
   this.numComments = commentSvc.getAllForPhoto(this.getId());
   }
}

CommentService.java

@Service
public class CommentService{
   public List<CommentResource> getAllForPhoto(Long photoId) {
   // code to get all comments for photo
   }
}

Application.java

@SpringBootApplication
public class Application {
   public static void main(String[] args) {
      SpringApplication.run(Application.class);
   }
}

【问题讨论】:

  • 放弃未损坏的 bean 并坚持使用 Spring 管理的 bean 会容易得多。
  • 就这么简单的注释这个DTO吗?
  • 是的,应该是这样的
  • 另外,最佳实践是使用构造函数注入,它消除了导致此问题的隐藏依赖。

标签: java spring dependency-injection load-time-weaving


【解决方案1】:

除非您要求 Spring 容器管理 bean,否则 Spring 不会注入依赖项。为了将commentSvc 注入到PhotoResource 类中,您需要使用@Component 或@Bean 或@Service 对其进行注解,例如:

@Component
public class PhotoResource extends BaseRepresentable {
   @Autowired
   CommentService commentSvc;
}

并确保该类的包包含在@ComponentScan 包中。

另外,以下内容也无法编译:

@Service
public class CommentService(){

你不需要括号来声明一个类,它应该是:

@Service
public class CommentService{

【讨论】:

  • 谢谢您,现在尝试一下,但现在我无法启动应用程序,因为它抱怨找不到“PhotoEntity”类型的必需 bean。这是否意味着我需要将@Component 添加到每个类?另外,括号很好,当把它放在 SO 上时这是一个错字。
  • 因为它是构造函数所需要的。更改您的架构,除非绝对需要,否则不要创建 POJO,以及 @Autowire 一切
  • 是的,你需要@Autowire构造函数并注解PhotoEntity类。此外,您不需要对所有组件进行注释,只需对 Spring 管理的组件进行注释即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-23
  • 2012-10-18
  • 2013-12-26
  • 1970-01-01
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
相关资源
最近更新 更多