0

I'm relatively new to Spring Boot and dependency injection overall, so please forgive any noob things going on here. I'm building an API and am having trouble when injecting dependencies into a POJO resource (DTO).

When I call the method in the POJO this.numComments = commentSvc.getAllForPhoto(this.getId()); I am getting a NullPointerException. However, when I do this from another spring-managed bean and pass the values into the constructor, it works fine.

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.

In essence, my approach looks something like this:

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);
   }
}
orangeandgrey
  • 81
  • 2
  • 8

1 Answers1

2

Spring won't inject the dependency unless you ask the Spring container to manage the bean. In order for commentSvc to be injected into PhotoResource class, you need to annotate it with @Component or @Bean or @Service, e.g.:

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

And make sure the package of this class is included into @ComponentScan packages.

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{
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • Thank you, attempting this now, but now I can't start the application because it's complaining about a required bean of type 'PhotoEntity' could not be found. Does this mean I need to add @Component to every class? Also, good catch on the parenthesis, that was a typo when putting it onto SO. – orangeandgrey Jun 04 '17 at 18:56
  • 1
    Its because it is required by the constructor. Change your architecture, dont create POJOs unless absolutely needed, and @Autowire everyhing – Antoniossss Jun 04 '17 at 19:07
  • 1
    Yes, you need to `@Autowire` the constructor and annotate PhotoEntity class. Also, you don't need to annotate all the components, just the ones managed by Spring. – Darshan Mehta Jun 04 '17 at 19:21