【发布时间】: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