Solutons Lounge

How to deal with ArrayLists (Java) in Spring Boot? i.e. Autowiring/Dependency Injection


I was taking a online coding assessment where I was supposed to “refactor/fix” some Spring Boot API, and it had a Cart.java, Catalog.java, and Product.java Model classes, and if-I-recall-correctly (IIRC), the Product.java was the only Model class that had the @Component annotation (side question, but when to use @Component over @Entity for these type of model classes or POJOs or DTOs?), meaning, the other classes Cart.java and Catalog, where being instantiated using the “new” keyword, which looked utterly wrong to me.

Also, some of these classes, like Cart.java, had Class-level/fields that were data structures like Array Lists, and they were using the “new” keyboard inside the constructor to instantiate; is this correct? I kept getting “bean instantiation exception” errors and I had a feeling it was something to do with this, i.e. (ALSO, my questions are below!)

public class Cart {

   private List<Product> products;

   public Cart() {
      this.products = new ArrayList();
}

QUESTIONS:

  1. Is this ever good practice? Or should any type of Java POJO (plain-old-java-object), that is, a Model class that essentially has getters/setters should always be annotated to be a Spring Bean (or using XML/properties for older versions)?
  2. Regarding the data structures, like the Array Lists mentioned above, should they be declared using “new” keyword at the Class level/field level, or done inside the constructor like the sample code I posted?
  3. The code I was giving for the assessment also had a @PostConstruct method in the ShoppingCartService class, which of course was your typical service class. It had a try/catch block where it was using an ObjectMapper() and getResourceAsStream() method to read a products.json file that had sample dummy data; I kept getting exceptions like I said for beanInstantiation etc… and some for this public void init() method annotated with the @PostConstruct annotation that was in this ShoppingCartService – Shouldn’t all @PostConstruct methods be in the main SpringBootApplication, in this case, ShopApplication.java where the static void Main method lies?

Would appreciate any insight! Thanks!



Source link

Exit mobile version