简体   繁体   English

自动装配到非Spring托管类(POJO)中时发生NullPointerException-Spring Boot

[英]NullPointerException when autowiring into non-spring managed class (POJO) - Spring Boot

I'm relatively new to Spring Boot and dependency injection overall, so please forgive any noob things going on here. 我对Spring Boot和依赖项注入相对较新,因此请原谅这里发生的任何菜鸟事。 I'm building an API and am having trouble when injecting dependencies into a POJO resource (DTO). 我正在构建API,并且在将依赖项注入POJO资源(DTO)时遇到了麻烦。

When I call the method in the POJO this.numComments = commentSvc.getAllForPhoto(this.getId()); 当我在POJO中调用方法时, this.numComments = commentSvc.getAllForPhoto(this.getId()); I am getting a NullPointerException. 我收到了NullPointerException。 However, when I do this from another spring-managed bean and pass the values into the constructor, it works fine. 但是,当我从另一个受弹簧管理的bean进行此操作并将值传递到构造函数时,它可以正常工作。

After reading around, it looks like I need to do something with aspectJ and Load Time Weaving, but I'm not sure what that would look like in my code. 阅读后,看来我需要对AspectJ和“加载时间编织”进行一些操作,但是我不确定代码中的内容。

In essence, my approach looks something like this: 本质上,我的方法如下所示:

PhotoResource.java (POJO) 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 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);
   }
}

Spring won't inject the dependency unless you ask the Spring container to manage the bean. 除非您要求Spring容器来管理Bean,否则Spring不会注入依赖项。 In order for commentSvc to be injected into PhotoResource class, you need to annotate it with @Component or @Bean or @Service , eg: 为了将commentSvc注入PhotoResource类,您需要使用@Component@Bean@Service对其进行注释,例如:

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

And make sure the package of this class is included into @ComponentScan packages. 并确保此类的软件包包含在@ComponentScan软件包中。

Also, the following won't compile: 另外,以下内容不会编译:

@Service
public class CommentService(){

You don't need paranthesis to declare a class, it should be: 您不需要使用括号即可声明一个类,它应该是:

@Service
public class CommentService{

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM